CHAPTER 5: Building Java Web Applications with Spring Web MVC 259
- @Controller
- @RequestMapping("/addBook.html")
- public class AddBookController {
- BookValidator bookValidator;
- @Autowired
- public AddBookController(BookValidator bookValidator) {
- this.bookValidator = bookValidator;
- }
- @RequestMapping(value="/addBook.html", method = RequestMethod.GET)
- public String initForm(ModelMap model) {
- Book book = new Book();
- book.setBookTitle("Add Book :");
- model.addAttribute("book", book);
- return "addBook";
- }
- @InitBinder
- public void initBinder(WebDataBinder binder, WebRequest request) {
- binder.setDisallowedFields(new String[] {"author"});
- Book book = (Book)binder.getTarget();
- AuthorService authorService = new AuthorService();
- Long authorId = null;
- try {
- authorId = Long.parseLong(request.getParameter("author"));
- } catch (Exception e) {}
- if (authorId != null) {
- Author author = authorService.getAuthorById(authorId);
- book.setAuthor(author);
- }
- }
- @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);
- if(result.hasErrors()) {
- return "addBook";
- } else {
- bookService.createBook(book);
- return "redirect:/list_book.html";
- }
- }
- }