Spring 3 MVC Custom Validator Example

Spring provides Validator interface that we can use to validate objects. For defining custom validator we need to implement this interface.Validator interface has two methods as follows which we need to override.

  • ¬†public boolean supports(Class classname)
  • ¬†public void validate(Object obj, Errors errorObj)

In supports() method we need to declare that which bean class our validator can validate and validate() method contains the logic for validating the bean class properties like name,email,address.

Here I am going to describe the way to validate a user registration form easily by custom validator.

Required Steps

  • Add spring jars to WEB-INF/lib
  • Define Bean Class
  • Define Custom Validator
  • Define Controller class
  • Define JSP files register and success pages.

User.java

package com.startwithjava.beans;
public class User {
    private String name;
    private String email;
    private String address;
    private String country;
    private String state;
    private String city;
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
    
 

}

UserValidator.java

package com.startwithjava.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.startwithjava.beans.User;
@Component
public class UserValidator implements Validator
{
 
    public boolean supports(Class clazz) {
        return User.class.equals(clazz);
    }
	public void validate(java.lang.Object arg0, Errors arg1) {
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "name.required", "Name is required.");
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "email", "Name.required", "Email is required.");
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "address", "name.required", "Address is required.");
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "country", "country.required", "Country is required.");
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "state", "state.required", "State is required.");
		  ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "city", "city.required", "City is required.");
	}
 
}

RegisterController.java

package com.startwithjava.controllers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
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.startwithjava.beans.User;
 
/**
 * 
 * @author com.startwithjava
 *
 */
@Controller
public class RegisterController {
	 @Autowired
	    @Qualifier("userValidator")
	    private Validator validator;
	 
	    @InitBinder
	    private void initBinder(WebDataBinder binder) {
	        binder.setValidator(validator);
	    }
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String viewLogin(Map<String, Object> model) {
        User user = new User();
        model.put("userForm", user);
        return "register";
    }
 
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin(@ModelAttribute("userForm") User userForm,
            BindingResult result, Map<String, Object> model) {
    	validator.validate(userForm, result);
    	System.out.println("Email:"+userForm.getEmail());
        if (result.hasErrors()) {
            return "register";
        }else{
 
        	return "success";
        }
    }
}

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<style>
    .error {
        color: red; font-weight: bold;
    }
</style>
</head>
<body>
<div align="center">
<h2>Spring MVC Form Validation Demo - Register Form</h2>
<table border="0" width="90%">
        <form:form action="login" commandName="userForm">
<tr>
<td align="left" width="20%">Name: </td>
<td align="left" width="40%"><form:input path="name" size="30"/></td>
<td align="left"><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td align="left" width="20%">Email: </td>
<td align="left" width="40%"><form:input path="email" size="30"/></td>
<td align="left"><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td align="left" width="20%">Address: </td>
<td align="left" width="40%"><form:textarea path="address" col="30" rows="10"/></td>
<td align="left"><form:errors path="address" cssClass="error"/></td>
</tr>
<tr>
<td>Country: </td>
<td><form:password path="country" size="30"/></td>
<td><form:errors path="country" cssClass="error"/></td>
</tr>
<tr>
<td>State: </td>
<td><form:password path="state" size="30"/></td>
<td><form:errors path="state" cssClass="error"/></td>
</tr>
<tr>
<td>City: </td>
<td><form:password path="city" size="30"/></td>
<td><form:errors path="city" cssClass="error"/></td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit" value="Register"/></td>
<td></td>
</tr>
</form:form>
        </table>
</div>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Validation By StartWithJava</title>
</head>
<body>


<h1>Thanks for registering with us</h1>


</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ChatApplication</display-name>
  <welcome-file-list>
    <welcome-file>register.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

spring-servlet.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:p="http://www.springframework.org/schema/p" 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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <mvc:annotation-driven />
	<context:component-scan base-package="com.startwithjava"/>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
     <bean id="userValidator" class="com.startwithjava.validators.UserValidator" />
    </beans>

Leave a Reply