Learn Java for Web Development

(Tina Meador) #1
CHAPTER 5: Building Java Web Applications with Spring Web MVC 259


  1. @Controller

  2. @RequestMapping("/addBook.html")

  3. public class AddBookController {

  4. BookValidator bookValidator;



  5. @Autowired

  6. public AddBookController(BookValidator bookValidator) {

  7. this.bookValidator = bookValidator;

  8. }



  9. @RequestMapping(value="/addBook.html", method = RequestMethod.GET)

  10. public String initForm(ModelMap model) {

  11. Book book = new Book();

  12. book.setBookTitle("Add Book :");

  13. model.addAttribute("book", book);

  14. return "addBook";

  15. }



  16. @InitBinder

  17. public void initBinder(WebDataBinder binder, WebRequest request) {

  18. binder.setDisallowedFields(new String[] {"author"});

  19. Book book = (Book)binder.getTarget();

  20. AuthorService authorService = new AuthorService();

  21. Long authorId = null;

  22. try {

  23. authorId = Long.parseLong(request.getParameter("author"));

  24. } catch (Exception e) {}

  25. if (authorId != null) {

  26. Author author = authorService.getAuthorById(authorId);

  27. book.setAuthor(author);

  28. }

  29. }



  30. @ModelAttribute("authorList")

  31. public List populateAuthorList() {

  32. AuthorService authorService = new AuthorService();

  33. return authorService.getAuthorList();

  34. }



  35. @RequestMapping(method = RequestMethod.POST)

  36. public String processSubmit(@ModelAttribute("book") Book book, BindingResult result,
    SessionStatus status) {

  37. BookService bookService = new BookService();

  38. bookService.createBook(book);

  39. if(result.hasErrors()) {

  40. return "addBook";

  41. } else {

  42. bookService.createBook(book);

  43. return "redirect:/list_book.html";

  44. }



  45. }

  46. }

Free download pdf