CHAPTER 5: Building Java Web Applications with Spring Web MVC 247
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
As soon as the user requests a list of books using http://localhost:8080/bookstore, the request
hits the servlet engine, which routes the call to the bookstore web app, which is deployed in the
servlet container. The web.xml file shown in Listing 5-40 provides the welcome file that should serve
the request.
/list_book.html
The URL in the welcome file matches the URL pattern that has been registered for DispatcherServlet,
and the request is routed to it. Based on the configuration available in bookstore-servlet.xml, the
request is routed to a specific controller, illustrated in line 12 of Listing 5-41. Here the list_book.html
file is declared as a bean and mapped to the BookController class. This means if a URL with
/list_book.html is requested, it will ask the BookController to handle the request. Listing 5-42
illustrates the interface-based BookController. Later you will see how to replace this interface-based
controller with an annotated controller.
Listing 5-42. Interface-Based Controller for the Bookstore Application
- package com.apress.bookstore.controller;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.Controller;
- import com.apress.bookstore.service.BookService;
- public class BookController implements Controller{
- @Override
- public ModelAndView handleRequest(HttpServletRequest arg0,
- HttpServletResponse arg1) throws Exception {
- BookService bookservice = new BookService();
- ModelAndView modelAndView = new ModelAndView("bookList");
- modelAndView.addObject("bookList", bookservice.getBookList());
- return modelAndView;
- }
- }
The controller instantiates the BookService that is responsible for returning the required book data.
ModelAndView("booklist") calls the view named bookList by passing bookList to Spring’s view