Spring MVC Form Validation Annotation Example

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.

Notices: On validation part, we will use the hibernate-validator library in this example.

Project structure
The project structure should be such as below:
Spring MVC Form Validation Annotation Example

Controller Endpoint
The Employee POJO will be acts as a bean to the form holding data that user will input via form.

The controller is responsible to serve the GET and POST request to create the model to the form and response the validation message.

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

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:

and contains the content

The above messages flow the below pattern

Create the view
We will create the employee.jsp view that contains a form such as the below code snippet

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
Spring MVC Form Validation Annotation Example form

Now, we try to submit form without input data we will get validation errors as the below picture
Spring MVC Form Validation Annotation Example errors

Next, we fill all data on the form and click submit then the form submission will pass the validation.
Spring MVC Form Validation Annotation Example input
The success page will display
Spring MVC Form Validation Annotation Example success

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 (89 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons