Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on the server-side.

Bean Validation API

From Spring framework version 4 and above, the Spring framework supports Bean Validation 1.0 (JSR-303) and Bean Validation 1.1 (JSR-349).

Below is given an annotation used for validation:

@Valid – The @Valid annotation is used to annotate a method parameter, property, or method return type for validation. It is used to annotate a model object that we want to validate.

BindingResult – It is an interface that represents the binding results. It extends an interface for error registration, allowing a validator to be applied, and adds binding-specific analysis.

Validation Annotations

A variety of annotations are used in Spring MVC form Validation, which is available in javax.validation.constraints package.

Following is the list of commonly used Validation annotations:

Annotations Description
@Size It specifies that the size of the annotated element must be between the specified boundaries.
@Pattern It specifies that the annotated CharSequence must match the regular expression.
@Past It specifies that the annotated element must be a date in the past.
@Null It specifies that the annotated element must be null.
@NotNull It specifies that the annotated element should not be null.
@Min It specifies that the annotated element must be a number whose value must be equal or greater than the specified minimum number.
@Max It specifies that the annotated element must be a number whose value must be equal or smaller than the specified maximum.
@Future It specifies that the annotated element must be a date in the future.
@Digits It specifies that the annotated element must be a digit or number within the specified range. The supported types are short, int, long, byte, etc.
@DecimalMin It specifies that the annotated element must be a number whose value must be equal or greater than the specified minimum. It is very similar to @Min annotation, but theonly difference is it supports CharSequence type.
@DecimalMax It specifies that the annotated element must be a number whose value should be equal or smaller than the specified maximum. It is very similar to @Max annotation, but the only difference is it supports CharSequence type.
@AssertTrue It determines that the annotated element must be true.
@AssertFalse It determines that the annotated element must be false.

Example of Spring MVC Validation

Here, we are going to create an example of Spring MVC Validation using @Valid annotation in the Controller class.

Following are the steps to create an example of Spring Validator:

  • Create a request page

In this step, we are going to create a request page named index.jsp.

index.jsp

 <html>
 <body>
 <h2> Spring MVC Web application </h2>
 <a href = "cust-regis-form"> Customer Registration Form </a>
 </body>
 </html> 
  • Create a Model class

In this step, we are going to create a Model class named Customer.java, which stores the data. In the Customer class, we are going to use the @NotNull and @Size annotations on the “lname” variable. 

Customer.java

 import javax.validation.constraints.NotNull;
 import javax.validation.constraints.Size;
 public class Customer {
                 private String fname;
                 @NotNull
                 @Size(min = 3, message = " This field is required ")
                 private String lname;
                 public String getFname() {
                                 return fname;
                 }
                 public void setFname(String fname) {
                                 this.fname = fname;
                 }
                 public String getLname() {
                                 return lname;
                 }
                 public void setLname(String lname) {
                                 this.lname = lname;
                 }
  } 
  • Create the Controller

In this step, we are going to create the Controller named MainController.java, which returns the JSP view pages. In the Controller class, we are going to use the @Valid annotation and BindingResult for validation.

MainController.java

 import javax.validation.Valid;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
 @Controller
 public class MainController {
                 @RequestMapping("/cust-regis-form")
                 public String showCustomerForm(Model m) {
                                 m.addAttribute("customer", new Customer()) ;
                                 return "customerform" ;
                 }
                 @RequestMapping("/processForm")
                 public String showCustomerData( @Valid @ModelAttribute("customer") Customer custom,
                                                 BindingResult thebindingresult) {
                                 if (thebindingresult.hasErrors()) {
                                                 return "customerform" ;
                                 }
                                 else {
                                                 return "customerformdata" ;
                                 }
     }
  } 
  • Add the entry of controller into web.xml

In this step, we are going to add the entry of the Controller inside the web.xml file.

web.xml

 <?xml version = "1.0" encoding = "UTF-8"?>
 <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
                 xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
                 xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
                 id = "WebApp_ID" version = "3.1">
                 <display-name>spring-mvc-demo</display-name>
                 <absolute-ordering />
                 <!-- Spring MVC Configs -->
                 <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
                 <servlet>
                                 <servlet-name>dispatcher</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>
                 <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
                 <servlet-mapping>
                                 <servlet-name>dispatcher</servlet-name>
                                 <url-pattern>/</url-pattern>
                 </servlet-mapping>
 </web-app> 
  • Add the entry of Model into another XML file

In this step, we are going to define the Model/ bean into another XML file named spring-servlet.xml.

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: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.xsd">
                 <!-- Step 3: Add support for component scanning -->
                 <context:component-scan base-package = "com.app.SpringMVCValidation"  />
                 <!-- Step 4: Add support for conversion, formatting and validation support -->
                 <mvc:annotation-driven/>
                 <!-- Step 5: Define Spring MVC view resolver -->
                 <bean
                                 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                                 <property name = "prefix" value = "/WEB-INF/view/" />
                                 <property name = "suffix" value = ".jsp" />
                 </bean>
 </beans> 
  • Create other JSP pages

In this step, we are going to create the other view pages (JSP pages).

customerform.jsp

 <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
 <!DOCTYPE html>
 <html>
 <head>
 <meta charset = "ISO-8859-1">
 <title> Customer Form </title>
   <style>
        .error {color:red}
    </style>
 </head>
 <body>
 <h3><i>The field with Asterisk(*) mark is required.</i></h3>
 <form:form action = "processForm" modelAttribute = "customer" >
 FIRST NAME: <form:input path = "fname" />
 <br></br>
 LAST NAME (*): <form:input path = "lname" />
   <form:errors path = "lname" cssClass = "error" >
   </form:errors>
 <br></br>
 <input type = "submit" value = "Submit" />
  </form:form>
 </body>
 </html> 

customerformdata.jsp

 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
 <!DOCTYPE html>
 <html>
 <head>
 <title>Customer data</title>
 </head>
 <body>
 The customer is confirmed: ${customer.fname} ${customer.lname}
 </body>
 </html> 

Output

Spring MVC Form Validation
Spring MVC Form Validation 1
Spring MVC Form Validation 2
Spring MVC Form Validation 3
Spring MVC Form Validation 4

Whitespaces problem with required Validator

If we pass whitespaces in the required Validator field, the String containing only whitespaces will pass the Validation. For example, we have created the LAST NAME as the required field, and if we enter whitespaces in that field, it will pass the Validation.

Following output shows the whitespaces problem:

Spring MVC Form Validation 5
Spring MVC Form Validation 6
Spring MVC Form Validation 7

To overcome the discussed problem, we are going to use the @InitBinder annotation inside the Controller. The @InitBinder works as a pre-processor and used to trim the whitespaces before the Strings.

Spring MVC @InitBinder

The @InitBinder annotation is used to initialize the WebDataBinder, which is used for spreading commands and form object arguments of annotated handler methods.

For accessing the @InitBinder annotation, we need to write the given code snippet in the Controller named MainController.java class.

MainController.java

 @InitBinder
 public void initBinder(WebDataBinder dataBinder)  {
                 StringTrimmerEditor stringEditor = new StringTrimmerEditor(true);
                 dataBinder.registerCustomEditor(String.class,stringEditor ); 
}

 After using the @InitBinder, the problem of whitespaces is removed from the application, as only whitespaces in the text field didn’t pass the validation, shown in the output.

Spring MVC Form Validation 8
Spring MVC Form Validation 9

Related Topics

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.

Spring – Annotation-based Inversion of Control (IoC)

Spring – Annotation-based Inversion of Control (IoC) We have previously discussed an example of Spring IoC (Inversion of Control). In the previous case, we have used the bean-configuration file to define the bean...

3 minutes read.

Spring MVC Example – Reading HTML Form Data

We have discussed earlier a simple example of Spring MVC in which we have created multiple view pages. Here, we are going to create another Spring MVC example in which we are...

7 minutes read.

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.