Java Reference
In-Depth Information
A new controller, AddBookController , is added that takes care of all the form processing using
annotations. Listing 5-46 illustrates the AddBookController .
Listing 5-46. AddBookController for Form Processing
1. package com.apress.bookstore.controller;
2.
3. import java.util.List;
4.
5. import org.springframework.stereotype.Controller;
6. import org.springframework.ui.ModelMap;
7. import org.springframework.validation.BindingResult;
8. import org.springframework.web.bind.WebDataBinder;
9. import org.springframework.web.bind.annotation.InitBinder;
10. import org.springframework.web.bind.annotation.ModelAttribute;
11. import org.springframework.web.bind.annotation.RequestMapping;
12. import org.springframework.web.bind.annotation.RequestMethod;
13. import org.springframework.web.bind.support.SessionStatus;
14. import org.springframework.web.context.request.WebRequest;
15.
16. import com.apress.bookstore.model.Author;
17. import com.apress.bookstore.model.Book;
18. import com.apress.bookstore.service.AuthorService;
19. import com.apress.bookstore.service.BookService;
20.
21. @Controller
22. @RequestMapping("/addBook.html")
23. public class AddBookController {
24. @RequestMapping(value="/addBook.html", method = RequestMethod.GET)
25. public String initForm(ModelMap model) {
26. Book book = new Book();
27. book.setBookTitle("Add Book :");
28. model.addAttribute("book", book);
29. return "addBook";
30. }
31.
32. @InitBinder
33. public void initBinder(WebDataBinder binder, WebRequest request) {
34. binder.setDisallowedFields(new String[] {"author"});
35. Book book = (Book)binder.getTarget();
36. AuthorService authorService = new AuthorService();
37. Long authorId = null;
38. try {
39. authorId = Long.parseLong(request.getParameter("author"));
40. } catch (Exception e) {}
41. if (authorId != null) {
42. Author author = authorService.getAuthorById(authorId);
43. book.setAuthor(author);
44. }
45. }
46.
 
Search WWH ::




Custom Search