Thursday 6 December 2012

Spring MVC Form Validation

Posted by Naveen Katiyar On 10:02 No comments

Form Validation in spring MVC 3 Using Hibernate Validator(JSR 303)

Previous example shows how form handling is done in Spring MVC 3 using annotation. In this tutorial we will learn how Spring MVC uses Hibernate Bean Validator framework to apply form validation.

We will modify our previous example on Form Processing in Spring MVC 3 with Annotation to use Hibernate Bean Validator Framework (JSR 303 implementation).

Hibernate Bean Validator Framework uses annotations to apply validation rules on properties of a bean. To use Hibernate Bean Validator Framework with Spring MVC 3 we need to add some jar files related to bean validator and it’s dependencies. Following are the jar files we have to add :
  • hibernate-validator-4.0.2.GA.jar
  • log4j-1.2.16.jar
  • slf4j-api-1.5.10.jar
  • slf4j-log4j12-1.5.10.jar
  • javax.validation-1.0.0.GA.jar
Following are some of the annotations of Hibernate Validator that can be used to validate bean properties :
  1. @NotNull : Property can not be null. Applicable to class instances only, not to primitive types.
  2. @NotEmpty : Property can not be null or empty.
  3. @Null : Property should be null. Applicable to class instances only, not to primitive types.
  4. @Length : Used to define min and max length of a string.
  5. @NumberFormat : Can define a particular number format or style to String.
  6. @Min : Used to apply constraint on minimum value of number.
  7. @Max : Used to apply constraint on maximum value of number.
  8. @Valid : Applicable to an class instance. Class should also use Hibernate Validator constraint and the instance will be valid if all constraint defined in class are fulfilled.
  9. @AssertTrue : Applicable to boolean property only. The property must be true.
  10. @AssertFalse : Checks that the annotated elements are false;
  11. @CreditCardNumber : Used to check if a number is a credit card number or not.
  12. @DecimalMax : Applicable to BigDecimal, BigInteger,String,  byte, short,  int, long and respective wrapper classes. For min value check.
  13. @DecimalMin :  Applicable to BigDecimal, BigInteger,String,  byte, short,  int, long and respective wrapper classes. For max value check.
  14. @Future : Applicable to Date or Calender instance. The time must be in future means after today.
  15. @Past : Applicable to Date or Calender instance. The time must be in past means before today.
Now, lets start with example to implement the validation using hibernate bean validation in spring mvc 3. We will follow following steps to modify our previous example of form processing :
  1. First of all we will modify our command class (User.java) to include hibernate bean validation annotations.
  2. Then we will change our controller (RegistrationController.java) to include @Valid annotation.

User.java
Our command class User.java will be modified as follows to make the support of hibernate bean validation :
package com.naveen.domain;

import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;

public class User {
            @NotEmpty(message="Name field is mandatory.")
            private String name = null;
           
            @NotEmpty(message="Standard field is mandatory.")
            private  String standard = null;
            private int age;
            private String sex = null;
           
             @Length(max=10,min=10,message="Phone number is not valid. Should be of length 10.")
             @NotEmpty(message="Phone field is mendatory.") @NumberFormat(style= Style.NUMBER)
            private String phone=null;
             
            public String getPhone() {
                        return phone;
            }
            public void setPhone(String phone) {
                        this.phone = phone;
            }
            public String getName() {
                        return name;
            }
            public void setName(String name) {
                        this.name = name;
            }
            public String getStandard() {
                        return standard;
            }
            public void setStandard(String standard) {
                        this.standard = standard;
            }
            public int getAge() {
                        return age;
            }
            public void setAge(int age) {
                        this.age = age;
            }
            public String getSex() {
                        return sex;
            }
            public void setSex(String sex) {
                        this.sex = sex;
            }
           
            @Override
            public String toString() {
                        return "User [name=" + name + ", standard=" + standard + ", age=" + age
                                                + ", sex=" + sex + "]";
            }
}



You can apply our custom error message using “message” attributes in annotations. Other attributes are required as per the annotations.
RegistrationController.java
We have to change our controller class to work with annotation configurations.
package com.naveen.controllers;

import javax.validation.Valid;

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

import com.naveen.domain.User;

@Controller
@RequestMapping(value="/registration.htm")
public class RegistrationController {
           
            @RequestMapping(method=RequestMethod.GET)
            public String showForm(ModelMap model){
                        User user = new User();
                        model.addAttribute("USER", user);
                        return "registration";
            }

            @RequestMapping(method=RequestMethod.POST)
            public String processForm(@Valid @ModelAttribute(value="USER") User user,BindingResult result){
                        if(result.hasErrors()){
                                   
                                    return "registration";
                        }else{
                                    System.out.println("User values is : " + user);
                                    return "success";
                        }                      
            }
}




You can find a new thing in our controller class. Here is the explanation :
  • @Valid : the new annotation @Valid has been associated with the ModelAttribute or command instance. It is the part of the Hibernate Bean Validation. It will indicate to Spring MVC that the User instance should be a valid instance according to Hibernate Bean Validation Framework and if any error are there then put the errors in BindingResult instance.


Spring Configuration File

 spring-servlet.xml and web.xml in WEB-INF folder will remain same as of previous example.



Registration.jsp


<%@ page session="true" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                        <title>Hello World with Spring 3 MVC</title>
                        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
            </head>
            <body>
                        <h1>Registration Form</h1><br />
                        <form:form commandName="USER">
                        <table>
                                    <tr><td colspan="2"><form:errors path="*" cssStyle="color : red;"/></td></tr>
                                    <tr><td>Name : </td><td><form:input path="name" /></td></tr>
                                    <tr><td>Standard : </td><td><form:input path="standard" /></td></tr>
                                    <tr><td>Age : </td><td><form:input path="age" /></td></tr>
                                    <tr><td>Phone : </td><td><form:input path="phone" /></td></tr>
                                    <tr><td>Sex : </td><td><form:select path="sex">
                                                            <form:option value="Male"/>
                                                            <form:option value="Female"/>
                                    </form:select></td></tr>
                                    <tr><td colspan="2"><input type="submit" value="Save Changes" /></td></tr>
                        </table>
                        </form:form>
            </body>
</html>

Download Source Code

0 comments: