Spring MVC Form Validation
In this article, we are going to learn to validate user data on the server-side. It is one of the essential tasks that we need to perform while creating a web application.
To get user data in the valid form we need to validate it either on the client-side or server or both. Spring provides a @Valid
annotation to get valid form data and use Hibernate Validator API to validate data.
Hibernate Validator is an implementation API for Bean validation in the Spring framework. It provides several annotations to make a clean and simple validation integration with Java code. It works on both server and client application programming.
Hibernate Validator Annotations
The following are commonly used annotations for data validation in the Spring application.
Annotation
|
Description
|
@NotNull
|
It determines that the value can't be null.
|
@Min
|
It determines that the number must be equal or greater than the specified value.
|
@Max
|
It determines that the number must be equal or less than the specified value.
|
@Size
|
It determines that the size must be equal to the specified value.
|
@Pattern
|
It determines that the sequence follows the specified regular expression.
|
@Email
|
It checks whether the specified character sequence is a valid email address.
|
@NotEmpty
|
It checks whether the annotated element is not null nor empty.
|
@Null
|
It checks that the annotated value is null.
|
@Negative
|
It checks if the element is strictly negative. Zero values are considered invalid.
|
@NegativeOrZero
|
It checks if the element is negative or zero.
|
If you are using the maven project then add the following dependency to the pom.xml file. For the latest hibernate validator dependency, you can visit its official site.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.1.Final</version>
</dependency>
Spring MVC Form Validation Example
Let's understand by example and create a maven-based Spring project and add these files. After that run this example using web server (Apache Tomcat). See the source code of the project below.
// HomeController.java
It is a controller class file that uses @Controller
annotation. It has two methods, one is used to show the user form, and the second is used to validate the submitted user form.
package com.studytonight.controllers;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.studytonight.models.UserForm;
@Controller
public class HomeController {
@GetMapping("/userform")
public String index(@ModelAttribute("registration") UserForm registration) {
return "index";
}
@PostMapping("/userform")
public String register(@Valid @ModelAttribute("registration") UserForm registration, BindingResult result) {
if (result.hasErrors()) {
System.out.println("error");
return "index";
}
return "success";
}
}
// MainApp.java
This file contains code to create an IOC container for our application. The AnnotationConfigWebApplicationContext
class is used to create an object for application context.
package com.studytonight;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MainApp implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
context.close();
}
}
// AppConfig.java
This is a configuration file which is an alternate of the applicationContext.xml file that we created for the XML-based configuration example. The @Configuration
annotation indicates that this is not a simple class but a configuration class and the @ComponentScan
annotation is used to indicate the location of the component class in our spring project.
package com.studytonight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan("com.studytonight.controllers")
public class AppConfig implements WebMvcConfigurer{
@Autowired
ApplicationContext applicationContext;
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver ivr = new InternalResourceViewResolver();
ivr.setPrefix("/WEB-INF/views/");
ivr.setSuffix(".jsp");
ivr.setOrder(0);
return ivr;
}
}
// index.jsp
This is a JSP file that contains an HTML form that will be shown when the application runs.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Form</title>
<style type="text/css">
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
<form:form modelAttribute="registration">
<form:errors path="*" cssClass="errorblock" element="div" />
<br>
<label>Enter User Name </label>
<br>
<br>
<form:input path="name" />
<br>
<br>
<label>Enter Email </label>
<br>
<br>
<form:input path="email" />
<br>
<br>
<input type="submit" value="Register">
<br>
</form:form>
</body>
</html>
// success.jsp
This JSP file will be shown as a response if the user form is validated successfully.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Registered Successfully</h2>
</body>
</html>
// pom.xml
This file contains all the dependencies of this project such as spring jars, servlet jars, etc. Put these dependencies into your project to run the application.
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.studytonight</groupId>
<artifactId>springmvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.1.Final</version>
</dependency>
</dependencies>
<properties>
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
// UserForm.java
package com.studytonight.models;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
public class UserForm {
@NotEmpty(message = "Name can not empty")
String name;
String lastName;
@NotEmpty(message = "Email can not empty")
@Email
String email;
public UserForm(String name, String lastName, String email) {
this.name = name;
this.lastName = lastName;
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Run the Application
After successfully completing the project and adding the dependencies run the application using the server and you will get the output as below.
Submit Empty Form: Empty form validation
Email Error: Email Validation
Provide Correct Information
Form Submitted Successfully