Java Reference
In-Depth Information
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.<body>
2.<div id="centered">
3.
4.<jsp:include page="header.jsp" flush="true" />
5.<br />
6.<jsp:include page="leftColumn.jsp" flush="true" />
7.<span class="label">Featured Books</span>
8...........
9.</div>
10.</body>
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.<li><div><span class="label" style="margin-left: 15px;">Categories</span></div>
2.<ul>
3.<%
4.List<Category> categoryList1 = (List<Category>) application.getAttribute("categoryList");
5.Iterator<Category> iterator1 = categoryList1.iterator();
6.while (iterator1.hasNext()) {
7.Category category1 = (Category) iterator1.next();%>
8.<li><a class="label"href="<%=param1%>?action=category&categoryId=<%=category1.
getId()%>&category=<%=category1.getCategoryDescription()%>"><spanclass="label" style="margin-left:
30px;"><%=category1.getCategoryDescription()%></span></a>
9.</li>
10.<%}%>
11.</ul></li>
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.
 
Search WWH ::




Custom Search