Home  >  Spring Core

Validation Framework in Spring with Example

By Arvind Rai, August 18, 2013
In Spring, Validator framework plays the role of validating data and displaying the error message from property file. There is an interface org.springframework.validation.Validator in spring that handles the validation framework. Validator contains two methods as below.

1. Supports

Supports object matching and returns Boolean value.

2. Validate

This is the core method in validation framework that performs validation.

Maven File

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.concretepage</groupId>
  <artifactId>spring</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring</name>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>1.2.7.RELEASE</version>
    </dependency>
  </dependencies>
</project> 



Create Validator implementing Validator Interface

Find the our validator class.
UserValidator.java
package com.concretepage.validator;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.concretepage.bean.User;
public class UserValidator implements Validator {
	private Resource location;
        @Required
        public void setLocation(Resource location) {
                this.location = location;
        }
	@Override
	public boolean supports(Class cls) {
		return User.class.equals(cls);
	}
	@Override
	public void validate(Object ob, Errors err) {
		Properties props=null;
		try {
			 props = PropertiesLoaderUtils.loadProperties(location);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String msg1 = props.getProperty("errormsg.name");
		ValidationUtils.rejectIfEmpty(err, "name", "errormsg.name",msg1);
		User user = (User)ob;
		if(user.getAge()<18){
			String msg2 = props.getProperty("errormsg.age");
			err.rejectValue("age","errormsg.age",msg2);
		}
	}
} 
Inside the validator method , we can see the use of

PropertiesLoaderUtils

A utility class of spring that loads java.util.Properties.

ValidationUtils

A Utility class that has methods to invoke validator and checks for empty values by the method PropertiesLoaderUtils.loadProperties

Errors

Keeps the error message and exposes the data- binding for any object.

Now find the User class used in demo.
User.java
package com.concretepage.bean;
public class User {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 

Message Property File

messages_en.properties
errormsg.name = Name can not be blank.
errormsg.age = The age  entered is not valid.  

Create Bean for Validator

spring-app.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

  <bean id="user" class="com.concretepage.bean.User">
    <property name="name" value=""/>
    <property name="age" value="16"/>
   </bean>
   <bean id="userValidator" class="com.concretepage.validator.UserValidator">
   	    <property name="location" value="messages_en.properties"/>
   </bean>
</beans> 

Run Main Method using MapBindingResult


SpringDemo.java
package com.concretepage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;
import com.concretepage.bean.User;
import com.concretepage.validator.UserValidator;
public class SpringDemo {
   public static void main(String... args) {
    	 ApplicationContext context = new ClassPathXmlApplicationContext("spring-app.xml");
    	 User user = (User)context.getBean("user");
    	 UserValidator userValidator = (UserValidator)context.getBean("userValidator");
    	 Map<String,String> map = new HashMap<String,String>(); 
    	 MapBindingResult err = new MapBindingResult(map, User.class.getName());
    	 userValidator.validate(user, err);
    	 List<ObjectError> list = err.getAllErrors();
    	 for(ObjectError objErr : list){
    		 System.out.println(objErr.getDefaultMessage());
    	 }
    } 
} 

MapBindingResult

Acts as error holder for custom binding. It supports binding errors on Map attributes.

Find the output.
Name can not be blank.
The age  entered is not valid. 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us