Learn Java for Web Development

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

Step 5: Accessing the Model from the View

In the previous step, the controller forwards to the view home.jsp using the RequestDispatcher.


Listing 2-30 illustrates a fragment of home.jsp, which includes leftColumn.jsp. The leftColumn.jsp
file uses the model Category to display categories on the left menu of the home page.


Listing 2-30. Including leftColumn.jsp in home.jsp


1.
2.


3.
4.
5.

6.
7.Featured Books
8...........
9.

10.


   Line 6: The <jsp:include> tag is used to include leftColumn.jsp. This is done
because the left-side bar of the application (the menu) is common to all screens
in the application, but instead of writing the left-side bar in all screens, we write
it in one JSP page and include it wherever required as a means to reusability.
(In the next few chapters on web frameworks, we will see more advanced
techniques for reusing JSPs.)

Listing 2-31 illustrates the code fragment related to categories in leftColumn.jsp where the Category
is accessed.


Listing 2-31. Accessing the Category Model in leftColumn.jsp


1.

  • Categories

    2.

  •    Line 4: In this line, the category list is obtained from the ServletContext.
    We had saved the category list in the ServletContext obtained from the
    database in step 2.
     Line 6 to 10: The category details are displayed in the markup, such as the
    category description that you see on the home page.
    Free download pdf