CHAPTER 2: Building Web Applications Using Servlets and JSP 91
37.
38.
39.
40.
Line 30: url-pattern/books is mapped to the BookServlet in the <servlet-mapping>
element, which is mapped to the servlet class BookController on line 9.
Lines 20 to 27: We specify context parameters to the servlet in the web.xml
file, since context parameters are available to the entire web app. When a
servlet instance is created, its init() method is called by the servlet container.
The init() method allows a servlet to initialize itself before the first request
is processed. We override the init(ServletConfig config)method in the
BookController for getting the categories from the bookstore database.
These categories will be available to the entire application. The overridden
init(ServletConfig config) in the BookController is illustrated in Listing 2-28.
Step 2 and Step 3: Accessing DB via DAO to Get the Categories from the
Database and Setting the Categories in the Model
Listing 2-28 shows the BookController.
Listing 2-28. init( ) Method in BookController
1.public void init(ServletConfig config) throws ServletException {
2.super.init(config);
3.BookDAO bookDao = new BookDAOImpl();
4.// calling DAO method to retrieve bookList from Database
5.List
6.ServletContext context = config.getServletContext();
7.context.setAttribute("categoryList", categoryList);
8.}
Line 5: This list of categories is obtained from the database by calling
findAllCategories() on the bookDao object.
Line7: The list of categories is set in the ServletContext so that the list is
available to the entire webapp.
Step 4: Dispatching to the View
As the init() method is completed in the previous step, the container calls the service() method of
the servlet (discussed in life-cycle methods of servlet). This method looks at the request, determines
the HTTP method, and invokes the matching doget() or dopost() on the servlet. Listing 2-29
illustrates the doGet() and doPost() methods of the servlet.