Wednesday, 13 July 2011

Using Resource Bundles with JSR 303 Validation and Spring 3 MVC Web-Apps

Even if your application doesn’t need to support different locales it’s always a good idea to separate the text displayed on your user’s screen from your Java code. In Spring 3 web-apps, this is usually done by using a ResourceBundleMessageSource to load a bunch of property files. My last blog demonstrated how to add JSR 303 Bean Validation to a Spring web-app, and you may remember that the error messages that were displayed on the screen were embedded in the Java code as message attributes on the JSR 303 constraint annotations. For example:

public class SearchCriteria extends FrameworkBean {

@NotEmpty(message = "Event type may not be null")
@Size(min = 4, max = 4, message = "EventType must be length four")
private String eventType;

This is not a good idea. Last month I demonstrated how to access Spring resource bundles from within your JSP. This blog builds on that idea and demonstrates how to add error messages to your property files that are related to your JSR 303 annotations, and can be displayed by your JSPs. All this sounds complicated, but it isn’t, it’s just not that well documented. Assuming that you’re already using a ResourceBundleMessageSource, then all you need to do is to add a few entries into your property file - one for each annotation on each attribute of each command object. The format is:

{constraint-name}.{command-object-name}.{attribute-name}=My Error Message Text

Given the Java code snippet above, then we can add the following to our property file for the eventType attribute of the searchCriteria command object:

NotEmpty.searchCriteria.eventType=Event type may not be empty
Size.searchCriteria.eventType=EventType must be four characters

...which, when we have a validation error, will give us the following screen:

In this case, the error message has been displayed using Spring’s form:errors tag:

<form:errors path="eventType" />

No comments: