Learn Java for Web Development

(Tina Meador) #1

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



  1. public class BookController {

  2. @RequestMapping(method = RequestMethod.GET)

  3. public ModelAndView bookListController() {

  4. BookService bookManager = new BookService();

  5. ModelAndView modelAndView = new ModelAndView("bookList");

  6. modelAndView.addObject("bookList", bookManager.getBookList());

  7. return modelAndView;

  8. }

  9. }


   Line 8: In an annotations-based application, a form controller is created using
@Controller. @Controller indicates that a particular class serves the role of
a controller. @Controller also allows for autodetection, aligned with Spring’s
general support for detecting the component classes in the class path and
autoregistering bean definitions for them. In this example, the @Controller
annotation indicates that the BookListControler class is a controller class.
 Line 9: @RequestMapping is used to map URLs such as /list_book.html onto an
entire class or a particular handler method. @RequestMapping on the class level
indicates that all handling methods on this controller are relative to the
/list_book.html path.
 Line 13: @RequestMapping on the method level indicates that the method accepts
only GET requests; in other words, an HTTP GET for /list_book.html involves
bookListController().

Listing 5-45 illustrates the modified bookstore-servlet.xml to have the annotations-based
BookController discovered.


Listing 5-45. bookstore-servlet.xml to Support Annotations-Based Controller



  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans=
    "http://www.springframework.org/schema/beans"

  4. xmlns:context="http://www.springframework.org/schema/context"

  5. xsi:schemaLocation="http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

  6. http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd

  7. http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">




Documentation