It’s hard to imagine a web-application which doesn’t has some validation
logic for an user data. Almost all user’s data has some constraints,
e.g. date of birth should consist of day, month, year etc. Spring MVC
has its own solution for the data validation, and it’s become available
with the help of
Validator interface.
Usage of Spring MVC Validator
A validation make sense in time
when you receive some kind of data from users. An obvious way to do
this is to use web forms. The
Validator interface it is a means to implement the validation logic of entire Spring MVC application. Sounds promising.
There are three things which you need to do in order to start using the Validator:
- Create a validator class for some domain model and implment the Validator interface.
- Overload supports(Class clazz) method.
- Overload validate(Object target, Errors errors) method.
Now you know the basics of the
Validator interface usage. Enough of theory let’s go ahead with practice.
Exapmle of Vlidator Spring MVC
I want to demonstrate the
Validator
interface in action on one of my previous tutorials where a validation
will not be redundant. I mean the sample application with
Spring Data. First you need to update the pom.xml file, add the following dependency:
03 | < groupid >javax.validation</ groupid > |
04 | < artifactid >validation-api</ artifactid > |
05 | < version >1.0.0.GA</ version > |
08 | < groupid >org.hibernate</ groupid > |
09 | < artifactid >hibernate-validator</ artifactid > |
10 | < version >4.3.0.Final</ version > |
In the project I have the one POJO:
02 | @Table (name = "shops" ) |
11 | @Column (name = "employees_number" ) |
12 | private Integer emplNumber; |
14 | public Integer getId() { |
18 | public void setId(Integer id) { |
22 | public String getName() { |
26 | public void setName(String name) { |
30 | public Integer getEmplNumber() { |
34 | public void setEmplNumber(Integer emplNumber) { |
35 | this .emplNumber = emplNumber; |
So let’s create the validation rules for it:
- The “name” can’t be empty.
- The “emplNumber” can’t be empty.
- The “emplNumber” can’t be less then 1.
The validation class for these purposes will look like:
01 | import org.springframework.stereotype.Component; |
02 | import org.springframework.validation.Errors; |
03 | import org.springframework.validation.ValidationUtils; |
04 | import org.springframework.validation.Validator; |
06 | import com.spr.model.Shop; |
09 | public class ShopValidator implements Validator { |
11 | private final static String EMPLOYEES_NUMBER = "emplNumber" ; |
14 | public boolean supports(Class clazz) { |
15 | return Shop. class .isAssignableFrom(clazz); |
19 | public void validate(Object target, Errors errors) { |
20 | Shop shop = (Shop) target; |
22 | Integer emplNumber = shop.getEmplNumber(); |
24 | ValidationUtils.rejectIfEmpty(errors, "name" , "shop.name.empty" ); |
25 | ValidationUtils.rejectIfEmpty(errors, EMPLOYEES_NUMBER, "shop.emplNumber.empty" ); |
27 | if (emplNumber != null && emplNumber < 1 ) |
28 | errors.rejectValue(EMPLOYEES_NUMBER, "shop.emplNumber.lessThenOne" ); |
Notice
that I applied @Component annotation to the class because I’m planning
to inject it later into the ShopController. Here are an explanation of
the Validator’s methods:
supports(Class) – Can this Validator
validate instances of the supplied Class? validate(Object,
org.springframework.validation.Errors) – validates the given object and
in case of validation errors, registers those with the given Errors
object. For the additional information look at the javadoc of
ValidationUtils class. The messages which will be shown during validation should be placed in the “messages.properties” file:
1 | shop.name.empty = The "Shop name" field can't be empty. |
2 | shop.emplNumber.empty = The "Employees number" field can't be empty. |
3 | shop.emplNumber.lessThenOne = The number of employees can't be less then 1. |
Let’s move to the controller’s code:
03 | private ShopValidator shopValidator; |
06 | private void initBinder(WebDataBinder binder) { |
07 | binder.setValidator(shopValidator); |
10 | @RequestMapping (value= "/create" , method=RequestMethod.POST) |
11 | public ModelAndView createNewShop( @ModelAttribute @Valid Shop shop, |
13 | final RedirectAttributes redirectAttributes) { |
15 | if (result.hasErrors()) |
16 | return new ModelAndView( "shop-new" ); |
18 | ModelAndView mav = new ModelAndView(); |
19 | String message = "New shop " +shop.getName()+ " was successfully created." ; |
21 | shopService.create(shop); |
22 | mav.setViewName( "redirect:/index.html" ); |
24 | redirectAttributes.addFlashAttribute( "message" , message); |
The
code snippet above demonstrates the main things which you need to
perform in a controller layer in order to implement the validation:
- Autowiring of the validator.
- Adding of the validator to the InitBinder.
- Apply @Valid annotation to the model in the concrete controller.
And finally let’s look at the JSP:
04 | < form:form method = "POST" commandname = "shop" action = "${pageContext.request.contextPath}/shop/create.html" > |
09 | < td >< form:input path = "name" ></ form:input ></ td > |
10 | < td >< form:errors path = "name" cssstyle = "color: red;" ></ form:errors ></ td > |
13 | < td >Employees number:</ td > |
14 | < td >< form:input path = "emplNumber" ></ form:input ></ td > |
15 | < td >< form:errors path = "emplNumber" cssstyle = "color: red;" ></ form:errors ></ td > |
18 | < td >< input value = "Create" type = "submit" ></ td > |
Pay your attention on the form:errors tags, they are responsible for the displaying of the error messages.
Summary
The
Validator interface allows creation of the flexible validation layer
for each domain model object in your application. It’s a good
alternative for the standard JSR-303 validation annotations such as
@Min, @Max, @NotNull, @Size etc.