Learn Java for Web Development

(Tina Meador) #1

102 CHAPTER 2: Building Web Applications Using Servlets and JSP


When the user submits the search request (again, locating the servlet from the request), step 2is
executed, and this time the action has a value search. So, the search case in the doPost() method in
the BookController, shown in Listing 2-44, is executed.


Listing 2-44. doPost( ) in the BookController


1.protected void doPost(HttpServletRequest request,
2.HttpServletResponse response) throws ServletException, IOException {
3.String base = "/jsp/";
4.String url = base + "home.jsp";
5.String action = request.getParameter("action");
6.String category = request.getParameter("category");
7.String keyWord = request.getParameter("keyWord");
8.if (action != null) {
9.switch (action) {
10.case "allBooks":
11.findAllBooks(request, response);
12.url = base + "listOfBooks.jsp";
13.break;
14.case "category":
15.findAllBooks(request, response);
16.url = base + "category.jsp?category=" + category;
17.break;
18.case "search":
19.searchBooks(request, response, keyWord);
20.url = base + "searchResult.jsp";
21.break;
22.
23.}
24.}
25.RequestDispatcher requestDispatcher = getServletContext()
26..getRequestDispatcher(url);
27.requestDispatcher.forward(request, response);
28.}


   Line 18: The case search is executed, and the value of the action is search
 Line 19: The searchBooks() method is called. The searchBooks( ) is illustrated in
Listing 2-45.
 Line 20: Line 20 constructs the URL for the view.
 Line 26: The URL for the view is provided to the RequestDispatcher.

Listing 2-45 illustrates the searchBooks() helper method used by the controller to invoke the call on
the DAO.


Listing 2-45. searchBooks( ) in the BookController


1.private void searchBooks(HttpServletRequest request,
2.HttpServletResponse response, String keyWord)
3.throws ServletException, IOException {

Free download pdf