Friday 13 March 2015

Spring MVC: Validator and @InitBinder

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:
01...
02        <dependency>
03            <groupid>javax.validation</groupid>
04            <artifactid>validation-api</artifactid>
05            <version>1.0.0.GA</version>
06        </dependency>
07        <dependency>
08            <groupid>org.hibernate</groupid>
09            <artifactid>hibernate-validator</artifactid>
10            <version>4.3.0.Final</version>
11        </dependency>
12...
In the project I have the one POJO:
01@Entity 
02    @Table(name = "shops"
03    public class Shop { 
04 
05        @Id 
06        @GeneratedValue 
07        private Integer id; 
08 
09        private String name; 
10 
11        @Column(name = "employees_number"
12        private Integer emplNumber; 
13 
14        public Integer getId() { 
15            return id; 
16        
17 
18        public void setId(Integer id) { 
19            this.id = id; 
20        
21 
22        public String getName() { 
23            return name; 
24        
25 
26        public void setName(String name) { 
27            this.name = name; 
28        
29 
30        public Integer getEmplNumber() { 
31            return emplNumber; 
32        
33 
34        public void setEmplNumber(Integer emplNumber) { 
35            this.emplNumber = emplNumber; 
36        
37    }
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:
01import org.springframework.stereotype.Component;
02import org.springframework.validation.Errors;
03import org.springframework.validation.ValidationUtils;
04import org.springframework.validation.Validator;
05 
06import com.spr.model.Shop;
07 
08@Component
09public class ShopValidator implements Validator {
10 
11    private final static String EMPLOYEES_NUMBER = "emplNumber";
12 
13    @Override
14    public boolean supports(Class clazz) {
15        return Shop.class.isAssignableFrom(clazz);
16    }
17 
18    @Override
19    public void validate(Object target, Errors errors) {
20        Shop shop = (Shop) target;
21 
22        Integer emplNumber = shop.getEmplNumber();
23 
24        ValidationUtils.rejectIfEmpty(errors, "name", "shop.name.empty");
25        ValidationUtils.rejectIfEmpty(errors, EMPLOYEES_NUMBER, "shop.emplNumber.empty");
26 
27        if (emplNumber != null && emplNumber < 1)
28            errors.rejectValue(EMPLOYEES_NUMBER, "shop.emplNumber.lessThenOne");
29 
30    }
31 
32}
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:
1shop.name.empty = The "Shop name" field can't be empty.
2shop.emplNumber.empty = The "Employees number" field can't be empty.
3shop.emplNumber.lessThenOne = The number of employees can't be less then 1.
Let’s move to the controller’s code:
01...
02    @Autowired
03    private ShopValidator shopValidator;
04 
05    @InitBinder
06    private void initBinder(WebDataBinder binder) {
07        binder.setValidator(shopValidator);
08    }
09...
10    @RequestMapping(value="/create", method=RequestMethod.POST)
11    public ModelAndView createNewShop(@ModelAttribute @Valid Shop shop,
12            BindingResult result,
13            final RedirectAttributes redirectAttributes) {
14 
15        if (result.hasErrors())
16            return new ModelAndView("shop-new");
17 
18        ModelAndView mav = new ModelAndView();
19        String message = "New shop "+shop.getName()+" was successfully created.";
20 
21        shopService.create(shop);
22        mav.setViewName("redirect:/index.html");
23 
24        redirectAttributes.addFlashAttribute("message", message);  
25        return mav;    
26    }
27...
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:
01<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
02...
03<h1>New Shop page</h1>
04<form:form method="POST" commandname="shop" action="${pageContext.request.contextPath}/shop/create.html">
05<table>
06<tbody>
07<tr>
08<td>Shop name:</td>
09<td><form:input path="name"></form:input></td>
10<td><form:errors path="name" cssstyle="color: red;"></form:errors></td>
11</tr>
12<tr>
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>
16</tr>
17<tr>
18<td><input value="Create" type="submit"></td>
19<td></td>
20<td></td>
21</tr>
22</tbody>
23</table>
24</form:form>
25...
Pay your attention on the form:errors tags, they are responsible for the displaying of the error messages.
Spring-MVC-Validator

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.

No comments:

Post a Comment