This tutorial shows Spring MVC Form Validation Annotation Example that uses Spring Form Tags, Form Validation with JSR-303 validation annotations, hibernate-validators and MessageSource. And these are all using annotation-based configuration.
Table of contents:
1. Maven Dependency
2. Project structure
3. Controller Endpoint
4. Spring MVC Java configuration
5. Create the view
6. Deploy Spring MVC Form Validation Annotation Example
Other interesting posts you may like
Maven Dependency
We need to use the following dependencies that supports to create excel document and pdf document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.spring.mvc</groupId> <artifactId>Form-Validation-Example</artifactId> <version>1.0.0</version> <name>SPRING-MVC - ${project.artifactId}</name> <url>http://javabycode.com</url> <packaging>war</packaging> <properties> <springframework.version>4.3.0.RELEASE</springframework.version> <hibernate.validator.version>5.2.4.Final</hibernate.validator.version> <javax.validation.version>1.1.0.Final</javax.validation.version> </properties> <dependencies> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <!-- jsr303 validation dependencies--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>${javax.validation.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.validator.version}</version> </dependency> <!-- Servlet dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>Form-Validation-Example</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>Form-Validation-Example</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> |
Notices: On validation part, we will use the hibernate-validator library in this example.
Project structure
The project structure should be such as below:
Controller Endpoint
The Employee POJO will be acts as a bean to the form holding data that user will input via form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package com.javabycode.model; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; public class Employee implements Serializable { @Size(min=3, max=25) private String firstName; @Size(min=3, max=25) private String lastName; @NotEmpty private String sex; @DateTimeFormat(pattern="dd/MM/yyyy") @Past @NotNull private Date birthDay; @Email @NotEmpty private String email; @NotEmpty private String country; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } |
The controller is responsible to serve the GET and POST request to create the model to the form and response the validation message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.javabycode.controller; import java.util.ArrayList; import java.util.List; 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 com.javabycode.model.Employee; @Controller @RequestMapping("/") public class MyController { @RequestMapping(method = RequestMethod.GET) public String newProfile(ModelMap model) { Employee employee = new Employee(); model.addAttribute("employee", employee); return "employee"; } @RequestMapping(method = RequestMethod.POST) public String saveProfile(@Valid Employee employee, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "employee"; } model.addAttribute("success", "Dear " + employee.getFirstName() + " , your profile completed successfully"); return "success"; } /* * Method used to populate the country list in view. */ @ModelAttribute("countries") public List<String> initializeCountries() { List<String> countries = new ArrayList<String>(); countries.add("USA"); countries.add("Canada"); countries.add("France"); countries.add("Indonesia"); countries.add("Australia"); countries.add("Other"); return countries; } } |
Let’s dig deeper
The saveProfile method is annotated with @RequestMethod.POST and handle the form POST requests. The annotation @Valid ensures Spring validate the Employee object. The BindingResult object will contains the result of this validation or any validate error.
Spring MVC Java configuration
We need to configure the WebMvcConfigurerAdapter such as below (If you want to understand more deeply about WebMvcConfigurerAdapter, please refer this tutorial Spring MVC Annotation Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.javabycode.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.javabycode") public class MyWebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } } |
Here, the messageSource method configures a Message bundle to support message property file. Spring will search for a file named messages.properties in class path. This file should be located as below:
1 |
src/main/resources/messages.properties |
and contains the content
1 2 3 4 5 6 7 8 |
Size.employee.firstName=First Name must be between {2} and {1} characters Size.employee.lastName=Last name must be at least {1} characters NotEmpty.employee.sex=Please select your gender NotNull.employee.birthDay=Please input date of birth Past.employee.birthDay=Date of birth must be in the past Email.employee.email=Please provide a valid Email address NotEmpty.employee.email=Please input email NotEmpty.employee.country=Please select your country |
The above messages flow the below pattern
1 |
{ValidationAnnotation}.{modelObject}.{fieldName} |
Create the view
We will create the employee.jsp view that contains a form such as the below code snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<%@ 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="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Profile Employee</title> </head> <body> <h1>Profile Employee</h1> <form:form method="POST" modelAttribute="employee"> <table> <tr> <td><label>First Name</label></td> <td><form:input type="text" path="firstName" id="firstName" /> <form:errors path="firstName" style="color:red" /></td> </tr> <tr> <td><label>Last Name</label></td> <td><form:input type="text" path="lastName" id="lastName" /> <form:errors path="lastName" style="color:red" /></td> </tr> <tr> <td><label>Sex</label></td> <td><form:radiobutton path="sex" value="M" />Male <form:radiobutton path="sex" value="F" />Female <form:errors path="sex" style="color:red" /></td> </tr> <tr> <td><label>Date of birth</label></td> <td><form:input type="text" path="birthDay" id="birthDay" /> <form:errors path="birthDay" style="color:red" /></td> </tr> <tr> <td><label>Email</label></td> <td><form:input type="text" path="email" id="email" /> <form:errors path="email" style="color:red" /></td> </tr> <tr> <td><label>Country</label></td> <td><form:select path="country" id="country"> <form:option value="">Select Country</form:option> <form:options items="${countries}" /> </form:select> <form:errors path="country" style="color:red" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit"></td> </tr> </table> </form:form> </body> </html> |
Deploy Spring MVC Form Validation Annotation Example
After building the project by maven we deploy the file war on application server (Tomcat 8 for example). Access the address URL http://localhost:8080/Form-Validation-Example/ to see how it works:
Here is the screen shoot
Now, we try to submit form without input data we will get validation errors as the below picture
Next, we fill all data on the form and click submit then the form submission will pass the validation.
The success page will display
That’s all on the tutorial Spring MVC Form Validation Annotation Example. Hope that it is usefull to you
Download complete source code of example, please click link below
Spring-MVC-Form-Validation-Annotation-Example.zip (381 downloads)