CHAPTER 5: Building Java Web Applications with Spring Web MVC 253
- @ModelAttribute("authorList")
- public List populateAuthorList() {
- AuthorService authorService = new AuthorService();
- return authorService.getAuthorList();
- }
- @RequestMapping(method = RequestMethod.POST)
- public String processSubmit(@ModelAttribute("book") Book book, BindingResult result,
SessionStatus status) {
- BookService bookService = new BookService();
- bookService.createBook(book);
- return "redirect:/list_book.html";
- }
- }
Line 22: The AddBookController class is annotated with
@RequestMapping("/addBook.html"), which means that all the methods in
this class will handle the request for the URL"/ addBook.html".
Line 24: The initialization for binding is done by annotating the method name
with @RequestMapping(method=RequestMethod.GET).
Line 25: initForm() handles the GET request type and shows the add new
book form.
Line 28: initForm() also adds a new instance to the model map so that the new
instance can be associated with the form.
Line 32: Binding is defined by annotating the method name with @InitBinder.
Annotating controller methods with @InitBinder allows configuring the web data
binding directly within the controller class. @InitBinder identifies methods that
initialize the WebDataBinder that is used to populate the command and form object
arguments of annotated handler methods. Such init-binder methods support all
arguments that @RequestMapping supports, except for command/form objects and
the corresponding validation result objects. Init-binder methods that are declared
must not have a return value. Thus, they are usually declared as void.
Line 33: Typical arguments include WebDataBinder in combination with WebRequest
or java.util.Locale, allowing code to register context-specific editors.
Data binding is configured using the WebDataBinder class. WebDataBinder is
a special DataBinder for data binding from web request parameters to
JavaBean objects.
Spring injects an instance of this class into any controller method that has been
annotated with @InitBinder. This object is then used to define the data binding
rules for the controller.
WebRequest allows for generic request parameter access as well as
request/session attribute access without ties to the native Servlet API.
Line 34: setDisallowedFields() registers the fields that are not allowed
for binding.