Spring MVC Form Validation using Annotation Tutorial with Example

When we accept user inputs in any web application, it become necessary to validate them. We can validate the user input at client side using JavaScript but it’s also necessary to validate them at server side to make sure we are processing valid data incase user has javascript disabled.

Spring MVC Framework supports JSR-303 specs by default and all we need is to add JSR-303 and it’s implementation dependencies in Spring MVC application. Spring also provides @Validator annotation and BindingResult class through which we can get the errors raised by Validator implementation in the controller request handler method.

Let’s create a simple Spring MVC project in Spring Tool Suite where we will use JSR-303 specs with it’s implementation artifact hibernate-validator. We will use annotation based form validation.

Step 1 :- Open Eclipse and Create Dynamic Web Project named SpringMVCFormSubmit

Step 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

Step 3 :- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • hibernate-validator-4.3.1.Final.jar
  • jboss-logging-3.1.0.GA.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
  • validation-api-1.0.0.GA.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 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.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk.controller" />
 
 <mvc:annotation-driven />
 
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.UrlBasedViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>
 
 <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
 <property name="basename" value="/WEB-INF/messages" />
 </bean>
 
 <!-- <context:property-placeholder
location="/WEB-INF/conf/messages.properties"/> -->
 
</beans>


STEP 5 :- Map Spring MVC in /WebContent/WEB-INF/web.xml file as below :-

<?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_3_0.xsd" version="3.0">
 <display-name>SpringMVCExample</display-name>
 <welcome-file-list>
 <welcome-file>login.html</welcome-file>
 </welcome-file-list>
 <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>*.html</url-pattern>
 </servlet-mapping>
</web-app>


STEP 6 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: FormController.java
package com.tutorialsdesk.controller;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
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.tutorialsdesk.model.User;

@Controller
public class FormController {
 
 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String viewLogin(Map<String, Object> model) {
 User user = new User();
 model.put("userForm", user);
 return "LoginForm";
 }
 
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public String doLogin(@Valid @ModelAttribute("userForm") User userForm,
 BindingResult result, Map<String, Object> model) {
 
 if (result.hasErrors()) {
 return "LoginForm";
 }
 
 return "LoginSuccess";
 }
}

Spring MVC will validate the model object annotated by the @Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method.

First we need to annotate model object that we want to validate with @Valid annotation. Then we need to have BindingResult argument in the method, spring takes care of populating it with error messages. The handler method logic is very simple, if there are any errors we are responding with the same page or else we are redirecting user to the success page.

Another important point to note is that we are adding “userForm” attribute to the model, this is necessary to let Spring framework know which model object to use in the form page. If we won’t do it, object binding to form data will not take place and our form validation will not work.

STEP 7 :- Create Model Class.
  • Package: com.tutorialsdesk.model
  • Filename: User.java
package com.tutorialsdesk.model;

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class User {

 @NotEmpty
 @Email
 private String email;
 
 @NotEmpty(message = "Please enter your password.")
 @Size(min = 6, max = 15, message = "Your password must between 6 and 15
characters")
 private String password;
 
 public String getEmail() {
 return email;
 }
 
 public void setEmail(String email) {
 this.email = email;
 }
 
 public String getPassword() {
 return password;
 }
 
 public void setPassword(String password) {
 this.password = password;
 }

}


STEP 8 :- Create LoginForm.jsp under WEB-INF/views folder.

<%@ 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 - Login Form</h2>
 <table border="0" width="90%">
 <form:form action="login.html" commandName="userForm">
 <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>Password: </td>
 <td><form:password path="password"
size="30"/></td>
 <td><form:errors path="password"
cssClass="error"/></td>
 </tr>
 <tr>
 <td></td>
 <td align="center"><input type="submit"
value="Login"/></td>
 <td></td>
 </tr>
 </form:form>
 </table>
 </div>
</body>
</html>

commandName="userForm" is used to set the name of the model attribute under which form object is exposed. It’s default value is “command” by default, hence we should set it to the model attribute name we are using in our controller classes.

form:errors is used to render the errors, if any, found when the page is rendered. path attribute is used to define the object property to be used for data binding. Rest of the code is standard HTML with some CSS for error messages styling.

STEP 9 :- Create LoginSuccess.jsp under WEB-INF/views folder.

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!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>Welcome</title>
</head>
<body>
 <div align="center">
 <h2>Welcome ${userForm.email}! You have logged in successfully.</h2>
 </div>
</body>
</html>

STEP 10 :- Create messages.propreties under WEB-INF folder.

If you want to localize the message, specify a key in the properties file in the following convention:
ConstraintName.CommandName.propertyName=validation error message

We localize validation error messages for the email field, so put the following key=value pairs in messages.properties file:

NotEmpty.userForm.email=Please enter your e-mail. 
Email.userForm.email=Your e-mail is incorrect.

STEP 11 :- Run your project enter below URL in your browser

http://localhost:8080/SpringMVCFormSubmit/
OR
http://localhost:8080/SpringMVCFormSubmit/login.html

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Form Submit and validation Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.