Let's update the code of AddController.java by following these steps:
- Add a method to bind the validator to WebDataBinder, and annotate it by @InitBinder, as follows:
@InitBinder private void initBinder(WebDataBinder webDataBinder) { webDataBinder.setValidator(validator); }
The @InitBinder annotation helps in identifying the methods that perform the WebDataBinder initialization.
- To enable the annotations to be considered by the framework, the book-servelt.xml file has to be updated:
- Add the mvc namespace as shown in the following configuration:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema
/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/
schema/beans http://www.springframework.org/schema/beans/
spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/
spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
You can only copy the highlighted statements in your existing code.
2. Add the configuration as follows:
<mvc:annotation-driven/>
- Update the addBook() method to add the @Valid annotation to perform book validation, and remove the validator.validate() invocation, as it will be executed implicitly. The updated code is as follows:
@RequestMapping("/addBook.htm") public ModelAndView addBook(@Valid @ModelAttribute("book") Book book,BindingResultbindingResult) throws Exception { //validator.validate(book, bindingResult); if(bindingResult.hasErrors()) { return new ModelAndView("bookForm"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("display"); //later on the list will be fetched from the table // rest of the code is same as the earlier implemenation }
- Run the application to get the similar result when you submit a blank form. The messages displayed in the view are hardcoded in the rejectValue() method. The framework provides a support for externalizing the messages in the properties file. Let's update the Validator for externalizing messages.