Skip to content

Commit

Permalink
add spring validator
Browse files Browse the repository at this point in the history
  • Loading branch information
phamthaithinh committed Apr 19, 2014
1 parent 9f455b0 commit 9cd2c49
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 10 deletions.
Empty file added .tgitconfig
Empty file.
21 changes: 18 additions & 3 deletions src/main/java/com/devjav/controller/AddEmployeeController.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,22 @@
package com.devjav.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.devjav.domain.Employee;
import com.devjav.form.EmployeeForm;
import com.devjav.service.EmployeeService;
import com.devjav.validator.EmployeeValidator;

/**
*
Expand All @@ -40,16 +45,21 @@ public AddEmployeeController() {
}

@RequestMapping(method = RequestMethod.GET)
public String add(Model model,HttpSession session) {
if(session.getAttribute("message")!=null){
public String add(Model model, HttpSession session) {
if (session.getAttribute("message") != null) {
model.addAttribute("message", "Insert employee successful.");
session.removeAttribute("message");
}
return getSuccessView();
}

@RequestMapping(method = RequestMethod.POST)
public String process(@ModelAttribute EmployeeForm employee,HttpSession session) {
public String process(
@ModelAttribute("employee") @Valid EmployeeForm employee,
BindingResult results, HttpSession session) {
if (results.hasErrors()) {
return getSuccessView();
}
Employee emp = new Employee();
emp.setEmail(employee.getEmail());
emp.setPhone(employee.getPhone());
Expand All @@ -66,4 +76,9 @@ public EmployeeForm createModelAttribute() {
return new EmployeeForm();
}

@InitBinder(value = "employee")
public void initBinder(WebDataBinder binder) {
binder.addValidators(new EmployeeValidator());
}

}
50 changes: 50 additions & 0 deletions src/main/java/com/devjav/validator/EmployeeValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* devjav [http://devjav.com]
* Copyright (C) 2014-2014 Pham Thai Thinh
* Contact:[email protected]
*
*/
package com.devjav.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.devjav.form.EmployeeForm;

/**
*
* @author Pham Thai Thinh
*
*/
public class EmployeeValidator implements Validator {
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(EmployeeForm.class);
}

public void validate(Object form, Errors errors) {
EmployeeForm employeeForm = (EmployeeForm) form;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"error.requried", new Object[] { "First name" });
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
"error.requried", new Object[] { "Last name" });

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone",
"error.requried", new Object[] { "Phone" });
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
"error.requried", new Object[] { "Email" });

if (!errors.hasFieldErrors("email")) {
if (!PatternValidator.validateEmail(employeeForm.getEmail())) {
errors.rejectValue("email", "error.invalid",
new Object[] { "Email" }, "Email is invalid format");
}
}
if (!errors.hasFieldErrors("phone")) {
if (!PatternValidator.validatePhone(employeeForm.getPhone())) {
errors.rejectValue("phone", "error.invalid",
new Object[] { "Phone" }, "Phone is invalid format");
}
}
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/devjav/validator/PatternValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* devjav [http://devjav.com]
* Copyright (C) 2014-2014 Pham Thai Thinh
* Contact:[email protected]
*
*/
package com.devjav.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
*
* @author Pham Thai Thinh
*
*/
public class PatternValidator {
private static String PHONE = "[0-9]{10}";
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

public static boolean validateEmail(String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean validatePhone(String phone) {
Pattern pattern = Pattern.compile(PHONE);
Matcher matcher = pattern.matcher(phone);
return matcher.matches();
}
}
11 changes: 11 additions & 0 deletions src/main/resources/messages.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#General use
error.invalid={0} is invalid format.
error.requried={0} is required.

#Add Employee Form
employee.form.title=Add Employee
employee.form.firstname=First name
employee.form.lastname=Last Name
employee.form.phone=Phone
employee.form.email=Email
#End Add Employee Form
9 changes: 7 additions & 2 deletions src/main/webapp/WEB-INF/spring/servlet/servlet-context.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
Expand All @@ -29,4 +29,9 @@
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="defaultEncoding" value="UTF-8" />
<beans:property name="basenames" value="classpath:messages"/>
</beans:bean>
</beans:beans>
26 changes: 21 additions & 5 deletions src/main/webapp/WEB-INF/views/add.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<style type="text/css">
.error{
color: red;
}
</style>
<spring:hasBindErrors name="employee">
<div class="error">
<h4>Oops!</h4>
<ul>
<c:forEach var="error" items="${errors.allErrors}">
<li><spring:message code="${error.code}"
arguments="${error.arguments}" text="${errMsgObj.defaultMessage}"></spring:message></li>
</c:forEach>
</ul>
</div>
</spring:hasBindErrors>
<c:if test="${not empty message}">
<div id="message" style="background-color: green">${message}</div></c:if>
<spring:url value="/manage/add.do" var="action" />
Expand All @@ -11,19 +27,19 @@
<table>
<tr>
<td>First Name</td>
<td><form:input path="firstName" /></td>
<td><form:input path="firstName" /><form:errors path="firstName" cssClass="error"/></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName" /></td>
<td><form:input path="lastName" /><form:errors path="lastName" cssClass="error"/></td>
</tr>
<tr>
<td>Phone</td>
<td><form:input path="phone" /></td>
<td><form:input path="phone" /><form:errors path="phone" cssClass="error"/></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
<td><spring:message code="employee.form.email"/> <span style="color: red">*</span></td>
<td><form:input path="email" /><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td colspan="1"><input type="submit" value="Submit"></td>
Expand Down

0 comments on commit 9cd2c49

Please sign in to comment.