Home  >  Spring MVC

Spring MVC Form Validation Using Annotations

By Arvind Rai, October 04, 2013
Form validation in Spring MVC is very simple. Annotation provides validation in very few lines of code. The error messages are picked up by properties file and error messages can be internationalized. Spring MVC needs validation API like hibernate validator. In our example we have a form which takes input as name, age and location. It has some validation to input value. If wrong values are entered, form will not be submitted and error messages will be displayed. The entire configuration required for error validation has been shown step by step.

Software Used

1. Java 7
2. Spring 3.1.0.RELEASE
3. Tomcat 7
4. Maven
5. Eclipse


Maven File

Find the maven file to build the project.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.concretepage.app</groupId>
  <artifactId>spring-mvc</artifactId>
  <version>1</version>
  <packaging>war</packaging>      
  <name>SpringMVC</name>
  <dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>3.1.0.RELEASE</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>3.1.0.RELEASE</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>3.0-alpha-1</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
          <groupId>javax.validation</groupId>
          <artifactId>validation-api</artifactId>
          <version>1.1.0.Final</version>
        </dependency>
       <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>5.0.1.Final</version>
       </dependency>
 </dependencies>
</project>  

@NotNull , @Size, @Min in Form Bean for Spring MVC Validation

In our form bean we are using validation like @NotNull , @Size, @Min. @NotNull ensures that the field can be blank. @Size defines the string as min and max. @Min declares the minimum size of data.
User.java
package com.concretepage.bean;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
        @NotNull
        @Size(min=5, max=20)
        private String name;
	@Min(5)
        private int age;
	@Size(min=5, max=50)
        private String location;
	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;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
} 

BindingResult in Spring MVC Controller for Validation

Spring MVC uses BindingResult and keeps all errors to display in jsp. In the code, first it is checked whether BindingResult has any error, if yes it returns form again.
UserController.java
package com.concretepage.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.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.concretepage.bean.User;
@Controller
public class UserController {
	@RequestMapping(value="user", method = RequestMethod.GET)
	public User user(){
		return new User(); 
	}
	@RequestMapping(value="createUser", method = RequestMethod.POST)
	public ModelAndView createUser(@ModelAttribute("user") @Valid User user,BindingResult result,ModelMap model) {
	        if(result.hasErrors()) {
	    	    return new ModelAndView("user");
	        }
		model.addAttribute("name",user.getName());
		model.addAttribute("age",user.getAge());
		model.addAttribute("location",user.getLocation());
		return new ModelAndView("redirect:pages/success.jsp");
	}
} 

<mvc:annotation-driven /> Configuration for Spring MVC Validation

Dispatcher servlet XML needs to be configured for with <mvc:annotation-driven /> to enable annotation driven validation in User Form. For the internationalization we need to configure MessageSource.
dispatcher-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: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.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

   <context:component-scan base-package="com.concretepage.controller" />
   <mvc:annotation-driven />
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix" value="/pages/"/>
	  <property name="suffix" value=".jsp"/> 
   </bean>
   <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="/WEB-INF/conf/messages" />
   </bean>
</beans> 

<form:errors> to Display Error in JSP

<form:errors> is used to display BindingResult in JSP. If we use <form:errors path="field_name"/> then it will display field specific error and if we use <form:errors/> without field name, it will display all errors.
user.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head><title>Create User</title></head>
<body>
  <form:form action="createUser" method="post" commandName='user'>
	   Enter User Name:<form:input  path="name"/>
	   <font color="red"> <form:errors path="name"></form:errors></font><br/>
	   Enter age :<form:input path="age"/>
	   <font color="red"><form:errors path="age"></form:errors></font><br/>
	   Enter location :<form:input path="location"/>
	   <font color="red"><form:errors path="location" ></form:errors></font><br/>
	   <input type="submit">
  </form:form>
</body>
</html> 

success.jsp
Name : ${param.name}<br/>
Age : ${param.age}<br/>
Location : ${param.location}<br/> 

messages_en.properties
NotEmpty.user.name=User Name can not be blank.
Size.user.name=User Name must be between 5 to 20 characters
Min.user.age= Minimum age must be 5 years
Size.user.location=Location must be between 5 to 50 characters 

web.xml for Spring MVC Validation

web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
	<display-name>Spring MVC Application</display-name>
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app> 

Run the Example of Spring MVC Validation

To run the application, use the example http://localhost:8080/spring-mvc-1/user . Find the output.

Spring MVC Form Validation Using Annotations

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us