Java Reference
In-Depth Information
23. @Controller
24. @RequestMapping("/addBook.html")
25. public class AddBookController {
26. BookValidator bookValidator;
27.
28. @Autowired
29. public AddBookController(BookValidator bookValidator) {
30. this.bookValidator = bookValidator;
31. }
32.
33. @RequestMapping(value="/addBook.html", method = RequestMethod.GET)
34. public String initForm(ModelMap model) {
35. Book book = new Book();
36. book.setBookTitle("Add Book :");
37. model.addAttribute("book", book);
38. return "addBook";
39. }
40.
41. @InitBinder
42. public void initBinder(WebDataBinder binder, WebRequest request) {
43. binder.setDisallowedFields(new String[] {"author"});
44. Book book = (Book)binder.getTarget();
45. AuthorService authorService = new AuthorService();
46. Long authorId = null;
47. try {
48. authorId = Long.parseLong(request.getParameter("author"));
49. } catch (Exception e) {}
50. if (authorId != null) {
51. Author author = authorService.getAuthorById(authorId);
52. book.setAuthor(author);
53. }
54. }
55.
56. @ModelAttribute("authorList")
57. public List<Author> populateAuthorList() {
58. AuthorService authorService = new AuthorService();
59. return authorService.getAuthorList();
60. }
61.
62. @RequestMapping(method = RequestMethod.POST)
63. public String processSubmit(@ModelAttribute("book") Book book, BindingResult result,
SessionStatus status) {
64. BookService bookService = new BookService();
65. bookService.createBook(book);
66. if(result.hasErrors()) {
67. return "addBook";
68. } else {
69. bookService.createBook(book);
70. return "redirect:/list_book.html";
71. }
72.
73. }
74. }
Search WWH ::




Custom Search