Form Validation in Spring MVC 3 using XML Configuration

This tutorial will show you how form validation is performed in Spring MVC 3 using xml configuration. While using xml configuration in Spring MVC, we have to create a class for our command object that will specify the code to validate the command object. Our validator class must implement the “org.springframework.validation.Validator” interface provided in Spring MVC jars to became a validator.

Validator Interface

We have to implement two method of org.springframework.validation.Validator interface.

  1. public boolean supports(Class<?> c) : In this method we specify which class instances will be validated with our validator. For example, there is a bean class name User and we are creating UserValidator class to validate the instance of User class then “support” method will specify that UserValidator class is for validating instances of User class.
  2. public void validate(Object command, Errors errors) : In this method we validate the command instance and if any error is present then the error is added to the Errors instance.

After creating the validator class we have to register the class with the controller on which we want to apply the validation. Our next example will illustrate how to use validation in Spring MVC 3 with practical approach.

In our example, we will create a registration form with different fields and will create a validator for this form.

We will follow following steps for implementing our example :

  1. First of all we will create a spring mvc command class (RegistrationBean.java), that will be used as a form bean in our example. The class will contain some properties on which we will apply the validation rules.
  2. Then we will implement our validator class (RegistrationValidator.java) that will implement org.springframework.validation.Validator interface of spring and will apply validation rules on the command class.
  3. After that, our form controller (RegistrationController.java) will be implemented that will extend SimpleFormController class. In our controller we will check if there is any error present our form values then form will be displayed again and if there is no error then we will show the success view.
  4. Form view jsp (registration.jsp) and success view jsp (success.jsp)will be implemented.
  5. Then we will configure our command class, validator class and controller class in spring mvc configuration file (app-config.xml).

RegistrationBean.java


package com.raistudies.domain;

public class RegistrationBean {
    private String name = null;
    private String username = null;
    private String email = null;
    private String phone = null;
    private String password = null;
    private String rePassword = null;
// Getter and setter are omitted to make code sort
}

There are six fields in our command class and following are the validation rules that will be applied to the fields :

  • All fields are mandatory.
  • Phone number should be a number and should be of length 10.
  • The value in password and rePassword should be same.

RegistrationValidator.java

Let us see how our validation class will implement above mentioned validation rules.


package com.raistudies.validator;

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

import com.raistudies.domain.RegistrationBean;

public class RegistrationValidator implements Validator {

    @Override
    public boolean supports(Class<?> c) {
        return RegistrationBean.class.isAssignableFrom(c);
    }

    @Override
    public void validate(Object command, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.name.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "field.username.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "field.email.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "field.phone.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.password.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "rePassword", "field.rePassword.empty");
        RegistrationBean regBean = (RegistrationBean)command;
        if(!regBean.getPassword().equals(regBean.getRePassword()))
            errors.rejectValue("rePassword","password.notmatch");
        if(regBean.getPhone().trim().length() != 10)
            errors.rejectValue("phone","field.phone.length");
        if(!isNumber(regBean.getPhone().trim()))
            errors.rejectValue("phone", "field.phone.NAN");
    }

    private boolean isNumber(String str){
        for (int i = 0; i < str.length(); i++) {
            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
            return false;
        }
        return true;
    }
}

Our RegistrationValidator class implements two methods of Validator interface :

  • return RegistrationBean.class.isAssignableFrom(c); : Returns true only if the command class associated with the form is assignable to the RegistrationBean class.
  • The validate method will be called on command object by the spring mvc. Errors class stores the errors occurs during the validation process. You can add your own error in Errors instance to to show it to the users.
  • ValidationUtils.rejectIfEmptyOrWhitespace(errors, “name”, “field.name.empty”); : Here ValidationUtils is a utility class provided in spring for performing common field error checking. We have to provide three parameters to the method “rejectIfEmptyOrWhitespace” which checks a string field against null and empty white space, where as first parameter is the Errors instance to which we want to add error, second parameter is the name of the field we want to validate and third one is for the key to the error message to be shown to the user.

RegistrationController.java

Our controllers class will extend SimpleFormController as we have seen in the form processing example and in onSubmit method we will check if any error occur during the validation process then form with error messages will be shown to the user and if there is no validation error then success view will be shown to the users.


package com.raistudies.controllers;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.raistudies.domain.RegistrationBean;

public class RegistrationController extends SimpleFormController{

    public RegistrationController(){
        setCommandClass(RegistrationBean.class);
        setCommandName("Registration");
    }

    @Override
    protected ModelAndView onSubmit(Object command, BindException errors)
    throws Exception {
        ModelAndView mv = new ModelAndView();
        if(errors.hasErrors()){
            mv.setViewName(getFormView());
        }else{
            mv.addObject("Registration", command);
            mv.setViewName(getSuccessView());
        }
        return mv;
    }
}

BindException instance will contain validation as well as data conversion errors.

registration.jsp

We will see one new thing our form jsp that is hoe to show form errors to the user.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Form Validation 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="Registration">
           <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>Username : </td><td><form:input path="username" /></td></tr>
                <tr><td>Email : </td><td><form:input path="email" /></td></tr>
                <tr><td>Phone : </td><td><form:input path="phone" /></td></tr>
                <tr><td>Password : </td><td><form:password path="password" /></td></tr>
                <tr><td>Retype Password : </td><td><form:password path="rePassword" /></td></tr>
                <tr><td colspan="2"><input type="submit" value="Register" /></td></tr>
            </table>
        </form:form>
    </body>
</html>

Here <form:errors/> tag shows errors associated with the path variable which is specified in “path” attribute. path=”*” means to show all errors in the associated form.

app-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Application Message Bundle -->
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
        <property name="cacheSeconds" value="3000" />
    </bean>

    <bean id="registrationValidator" class="com.raistudies.validator.RegistrationValidator"/>

    <bean name="/registration.htm" class="com.raistudies.controllers.RegistrationController">
        <property name="formView" value="registration"/>
        <property name="successView" value="success"/>
        <property name="validator" ref="registrationValidator"/>
    </bean>

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

To configure our validator with the controller class, we have to perform two steps :

  • First we have to register our validator class as a spring bean class (<bean id=”registrationValidator” class=”com.raistudies.validator.RegistrationValidator”/>).
  • Then we have to pass reference of our validator class as a property of name “validator” to the controller bean configuration(<property name=”validator” ref=”registrationValidator”/>).

Now, we have completed the implementation of our form validation example of spring mvc. Let us test the example by deploying the war file to Tomcat 6 server.

Hit the url in browser and you will get following form in your browser :

Form Validation in Spring MVC 3 using Annotation

Form Validation in Spring MVC 3 using Annotation

Then to try the validation functionality of spring mvc click on the “Register” button without filling any value, you will get following page :

Validation Errors in Spring MVC 3

Validation Errors in Spring MVC 3

Then fill the form data but do not fill same value on “Password” and “Retypr Password” field, you will get the following error :

Form Validation Error in Spring MVC 3 using Annotation

Form Validation Error in Spring MVC 3 using Annotation

If you fill be form correctly and then click on “Register” button , you will be redirected to the success page that will show the registration details :

Form Validation Success in Spring MVC 3 using Annotation

Form Validation Success in Spring MVC 3 using Annotation

In this way we can apply form validation in spring mvc while using xml based configuration. You can download code and war file of the form validation example in spring example from bellow links.

Source : Download

War : Download

Related Posts:

Leave a comment ?

7 Comments.

  1. app-config.xml c’est l’equivalence de quel fichier si j’utilise netbeans&Spring 3.0.2 release?

  2. Nice One.
    Could u plz tell me how to implement validations in Multi Action Controller.

  3. can you show the directory structure?
    I just want to know the jar files used here as I can’t download the war file :roll:

  4. How the message is received from messages.properties ?

Leave a Comment Cancel reply

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>