Learn Java for Web Development

(Tina Meador) #1

252 CHAPTER 5: Building Java Web Applications with Spring Web MVC


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. import java.util.List;



  3. import org.springframework.stereotype.Controller;

  4. import org.springframework.ui.ModelMap;

  5. import org.springframework.validation.BindingResult;

  6. import org.springframework.web.bind.WebDataBinder;

  7. import org.springframework.web.bind.annotation.InitBinder;

  8. import org.springframework.web.bind.annotation.ModelAttribute;

  9. import org.springframework.web.bind.annotation.RequestMapping;

  10. import org.springframework.web.bind.annotation.RequestMethod;

  11. import org.springframework.web.bind.support.SessionStatus;

  12. import org.springframework.web.context.request.WebRequest;



  13. import com.apress.bookstore.model.Author;

  14. import com.apress.bookstore.model.Book;

  15. import com.apress.bookstore.service.AuthorService;

  16. import com.apress.bookstore.service.BookService;



  17. @Controller

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

  19. public class AddBookController {

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

  21. public String initForm(ModelMap model) {

  22. Book book = new Book();

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

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

  25. return "addBook";

  26. }



  27. @InitBinder

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

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

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

  31. AuthorService authorService = new AuthorService();

  32. Long authorId = null;

  33. try {

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

  35. } catch (Exception e) {}

  36. if (authorId != null) {

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

  38. book.setAuthor(author);

  39. }

  40. }



Free download pdf