Data validation, conversion basics, custom error messages in Spring MVC

Web applications that accept input from a user, must not rely on the user to enter valid data. The system should recognize the invalid input and give the user an appropriate feedback.

With Spring MVC framework you can do it in a number of ways. It can be done through using annotations, manually, or you can even mix them. In this post we will cover the manual validation by calling the validation function. Stick around to find out how.

Lets create a Class first to which Spring can bind the populated data:

public class User {

    private 	String name;
    private 	int birthYear;

    // getters and setters


Next we need to update our controller, to get the data from the form:

@RequestMapping(value="/user", method=RequestMethod.POST)
public getUserForm(Model model, @ModelAttribute("user") User user, BindingResult result){

Normally the user object will hold the incoming user data, and the result object will hold the result of the binding.

Our users tend to make mistakes accidentally (or not :-) ) and enter for example string value instead of integer. In this case a conversion error will occur, and the error will be added to the result object.

We need to notify the user that an error has occurred, so we will write it out with the error tag:

<form:errors path="birthYear" />

This will result in a generic error message, so to customize it, we will create a properties file that will hold our version of the error message. First we need to register this new properties file in our dispatch-servlet.xml :

<bean id="messageSource" class="" p:basename="messages" />

This line means that a new bean will be registered to the application dispatch context, which will be a property file (resource file), with the name “messages”.

Next step is to create that file in the root of the project ( usually src\ )
By the way, this file will come in handy for all other notification messages, and we can even use it for localization, but that is a different topic which will not be covered in this post.

Lets insert the error message in the file:

typeMismatch = This is not a number!

Now, if we have a conversion error, the errors tag will write out the error message specified above.

But what if we have multiple conversions for which we need multiple error messages?
We can simply specify the error message for a Class conversion eg.: = A xxx value was expected!

In many situtations this is enough knowledge to deal with the data conversions.

Back to data validation:

In Spring MVC it is plain simple:

@RequestMapping(value="/user", method=RequestMethod.POST)
public postUserForm(Model model, @ModelAttribute("user") User user, BindingResult result){

	UserValidator userValidator = new UserValidator ();
	userValidator.validate(user, result);
	if (result.hasErrors() ){
		return getUserForm(user,model);
		// do something with valid user data

If the user object is not valid show the user form, if we have a valid user object we can process it.
It is a good practice to separate the controller’s code from the validation logic. It makes validation classes reusable, and keep the controller classes clean.
So, lets create the validator class:

public class UserValidator implements Validator{

	public boolean supports(Class c) {
		return User.class.equals(c);

	public void validate(Object obj, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "");

		User user = (User)obj;

		if (user.getBirthYear()!=null)
			if ( user.getBirthYear() <MINI_YEAR || user.getBirthYear() >MAX_YEAR)
				e.rejectValue( "birthYear", "user.birthYear.outOfInterval");

The supports(Class c) function gives back the class which can be validated with the validator.
And the validate() function validates the data.

The Spring Utils class called ValidationUtils can ease our job: if the user’s “name” property is empty or it only consist of whitespace, an error message “” should be written in the errors object. If we have our Resource bean defined in the dispatcher-servlet (explained above), Spring will search the error message in the file, and use the appropriate one.

And that is all for today.
Enyoj data conversion and validation!

To simplify data validation, annotations are available, see Spring MVC’s documentation.

Tagged with: ,
Posted in Google App Engine, Java, Spring
One comment on “Data validation, conversion basics, custom error messages in Spring MVC
  1. bitsniper says:

    Thank you! Finally got it. You rock!

1 Pings/Trackbacks for "Data validation, conversion basics, custom error messages in Spring MVC"
  1. [...] Data validation, conversion basics, custom error messages in Spring MVC [...]

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>