Learn Java for Web Development

(Tina Meador) #1
CHAPTER 2: Building Web Applications Using Servlets and JSP 95

Listing 2-32. All Books Link in leftColumn.jsp


1.


  •    Line 2: This line is the All Books link displayed in the menu. When this link is
    clicked, the value of action-allBooks is added to the URL as the parameter,
    as shown in the URL:

    http:localhost:8080/bookWeb/books?action=allBooks

    Step 2, which is locating the servlet from the request, is executed, but this time the action is not null
    and has a value allBooks. So, the code block in the doPost() method in the BookController, shown
    in Listing 2-33, is executed.


    Listing 2-33. All Books in the doPost( ) in 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 8: The action is not null, and the value of the action is allBooks.
     Lines 10 to 12: The helper method findAllBooks(request, response) is invoked,
    the URL is reconstructed to point to listOfBooks.jsp, and RequestDispatcher
    forwards to the view provided to the RequestDispatcher in the form of a URL.
    Free download pdf