Example on Validation with Spring MVC validator


Purpose: Validate the Registration form ( User details).
 All fields are mandatory, password and confirm password should be same

Technologies :
Spring 3
JDK1.6
Eclipse
Tomcat


Jar files 
commons-logging-1.1.1.jar
spring-asm-3.0.5.RELEASE.jar
spring-beans-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar
spring-core-3.0.5.RELEASE.jar
spring-expression-3.1.1.RELEASE.jar
spring-web-3.0.5.RELEASE.jar
spring-webmvc-3.0.5.RELEASE.jar
javax.validation-1.0.0.GA.jar




1)User Bean (User.java)
  
package com.form;

public class User {
    
 public String firstName;
 public String lastName;
 public String userId;
 public String passWord;
 public String confirmPassword;
 
 public String getFirstName() {
  return firstName;
 }
 
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public String getPassWord() {
  return passWord;
 }
 public void setPassWord(String passWord) {
  this.passWord = passWord;
 }
 public String getConfirmPassword() {
  return confirmPassword;
 }
 public void setConfirmPassword(String confirmPassword) {
  this.confirmPassword = confirmPassword;
 }

}
Validator (FormValidator.java)
package com.validator;

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

import com.form.User;

public class FormValidator implements Validator {

 @Override
 public boolean supports(Class arg0) {
  return User.class.equals(arg0);
 }

 @Override
 public void validate(Object obj, Errors e) {
   ValidationUtils.rejectIfEmpty(e, "firstName", "firstName.empty");
   ValidationUtils.rejectIfEmpty(e, "lastName", "lastName.empty");
   ValidationUtils.rejectIfEmpty(e, "userId", "userId.empty");
   ValidationUtils.rejectIfEmpty(e, "passWord", "passWord.empty");
   ValidationUtils.rejectIfEmpty(e, "confirmPassword", "confirmPassword.empty");
   
   User user = (User)obj;
   if(!user.passWord.equals(user.confirmPassword)){
    e.rejectValue("confirmPassword","confirmPassword.notequal");
   }
 }

}
More on ValidationUtils class.


Properties  (messages.properties)
firstName.empty=First Name should not be empty
lastName.empty=Last Name should not be empty
userId.empty=User ID should not be empty
passWord.empty=Pass Word should not be empty
confirmPassword.empty=Confirm Password should not be empty
confirmPassword.notequal=Confirm Password should be equal to Pass Word


Controller (RegistrationController.java)
package com.controller;


import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.form.User;
import com.validator.FormValidator;

@Controller
@RequestMapping("/")
public class RegistrationController {

  @InitBinder
     protected void initBinder(WebDataBinder binder) {
         binder.setValidator(new FormValidator());
     }
 
 
 @RequestMapping(method = RequestMethod.GET)
 public String registrationForm(ModelMap model) {
   User user = new User();
  model.addAttribute("user",user);
  return "registrationForm";
 
 }
 
 @RequestMapping(value = "/registration",method = RequestMethod.POST)
 public String submitForm(@Valid User  user, BindingResult result,ModelMap model) {
  
  if (result.hasErrors()) {
         return "registrationForm";
     }
  
  model.addAttribute("user",user);
  return "success";
 
 }
}
Note : Here we are setting the validator using "binder.setValidator(Validator)" within a @Controller's @InitBinder callback, and Adding the @Valid annotation to User class.

 Views ( registrationFrom.jsp and success.jsp)
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
 color: #ff0000;
}
 

</style>
</head>
 
<body>
 <h2>Registration Form</h2>
 
 <form:form method="POST" commandName="user" action="registration">
  
  <table>
   <tr>
    <td>First Name :</td>
    <td><form:input path="firstName" /></td>
    <td><form:errors path="firstName" cssClass="error" /></td>
   </tr>
   <tr>
    <td>Last Name :</td>
    <td><form:input path="lastName" /></td>
    <td><form:errors path="lastName" cssClass="error" /></td>
   </tr>
   <tr>
    <td>User Id :</td>
    <td><form:input path="userId" /></td>
    <td><form:errors path="userId" cssClass="error" /></td>
   </tr>
   <tr>
    <td>Pass word :</td>
    <td><form:password path="passWord" /></td>
    <td><form:errors path="passWord" cssClass="error" /></td>
   </tr>
   <tr>
    <td>Confirm Pass word :</td>
    <td><form:password path="confirmPassword" /></td>
    <td><form:errors path="confirmPassword" cssClass="error" /></td>
   </tr>
   <tr>
    <td colspan="3"><input type="submit" /></td>
   </tr>
  </table>
 </form:form>
 
</body>
</html>


<html>
<body>
Thank you ${user.firstName},
Your Registration successfully.
</body>
</html> 
Configuration (springvalidation-servlet.xml)


 
 
 
 
 
 
 
  
   /WEB-INF/views/
  
  
   .jsp
  
  
 
 
 
        
    


web.xml


  Spring Validation Demo
   
  springvalidation
  
                org.springframework.web.servlet.DispatcherServlet
                
  1
 
 
 
  springvalidation
  /
 
 
 
  contextConfigLocation
  /WEB-INF/springvalidation-servlet.xml
 
 
 
  
           org.springframework.web.context.ContextLoaderListener
         
 

Result :
URL :http://localhost:8080/SpringValidation

  •  Submit the form with empty values

  • Submit the form with incorrect pass word and confirm password
  • Submit the form with all correct values







1 comment:

  1. MEGA88 Casino, Ltd. Announces Return of $1.4B
    MEGA88 Casino, Ltd. Announces Return 포항 출장안마 of 원주 출장샵 $1.4B Largest 목포 출장샵 Ever 광주광역 출장안마 Return of the MEGA Mega Drive! MEGA88 영천 출장안마 Casino.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...