Learn Java for Web Development

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

We saw in the previous section that the categories are in leftColumn.jsp. Listing 2-35 illustrates the
code fragment for the category.


Listing 2-35. Categories Link on the Menu (leftColumn.jsp)


1.



    1. <span class="label"
      style="margin-left: 30px;"><%=category1.getCategoryDescription()%>

      3.


       Line 2: This is the link of the category displayed in the menu. When this link
    is clicked, the ID of the category and description and the name of the action
    category is added to the URL as the parameter, as shown in the following URL:

    http:localhost:8080/bookWeb/books?action=category&categoryId=1&category=clojure

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


    Listing 2-36. 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.}

  • Free download pdf