Spring MVC Validator Example

Spring MVC provides a Validator interface that we can use to validate objects.

In this lesson, we will see how to perform validation within Spring MVC using the Validator interface.

 

1. Technologies used

  • Spring 4.2.0.RELEASE
  • Maven 3.0.5
  • Eclipse 4.5
  • JDK 1.6
  • Tomcat 7.0

 

2. Project structure

SpringMVCValidatorExample-33

 

3. Project dependencies

We need to add Spring MVC dependencies:

 

4. Command object

We start by creating our form-backing object : User

 

5. JSP view

We create a simple form with two fields which are binded to our command object: User

File : index.jsp

We use the <form:errors .. /> tag to display errors if validation reports failures.

 

File : welcome.jsp

 

6. Validator

Now, we are going to define our validator by implementing org.springframework.validation.Validator

So, we need to provide implementation of two methods :

supports(..) : to tell that this validator will treat instances of the User class.

validate(..) : to validate the User object and in case of validation errors, registers those with the given Errors object

Here we put some validation logic in the validate(..) method.

 

 7. Controller

In the controller, we are going to validate the command object ‘user‘ posted back by the form.

To be able to use our validator, we need to inject an instance of the UserValidator into our controller.

We have used the UserValidator in the welcome(..) method.

The BindingResult object is used to collect the result of our validation, so all validation errors are added to the BindingResult argument. It must be placed directly after the user argument.

 

8. Spring MVC configuration

File : mvc-dispatcher-servlet.xml

 

9. Web app configuration

File : web.xml

 

10. Test It

URL : http://localhost:8080/SpringMVCValidatorExample/

Put invalid data and press the Submit button:

SpringMVCValidatorExample 1

 

If we provide correct information (Khadija, 24)

SpringMVCValidatorExample 2

 

Download source code

  • kamet saklani

    If I make age field blank and then submit the error is displayed as Failed to convert property value of type java.lang.String to required type int for property age; nested exception is java.lang.NumberFormatException: For input string: “”
    Age is required
    Age must be between 20 and 100
    Why I am getting the exception trace up there ? I am not even appending this exception log with the error message. Any suggestions.