Original PDF Flash format lab-6---combine-servlets,-jsps,-and-javabeans-lab-instructions  


Lab 6 Combine Servlets, Jsps, And Javabeans Lab Instructions

Lab 6 - Combine Servlets, JSPs, and JavaBeans
Lab Overview
In this lab, you will combine the servlets, JSP pages, and JavaBeans in the
OnlineStock System to create a working system that conforms to the principles of
the Model-View-Controller design pattern. As part of this integration process, you
will:
• Create the stock list processing servlet to retrieve data from the model layer
and populate the Java Bean you wrote in a previous exercise.
• Update the list stock JSP page to extract data from a JavaBean with the
<useBean> and <getProperty> tags and to format the data for viewing.
• Build a custom error reporting JSP page.


Lab Instructions
In this lab, you use the following steps to integrate the servlets, JSP pages,
and JavaBeans you have built in previous labs.
1. Create
the
StockListServlet servlet to retrieve a list of stock items from
the model layer, and populate a JavaBean with that data. You will also modify
the servlet to report errors using the sendError() servlet error reporting method.
2 Create the listStock.jsp to access the data in a JavaBean and construct an
HTML table with the data.
3 Create a custom error reporting JSP page, and register it in the Web
deployment descriptor.
4 Perform integration testing.

Step 1 SetUp Your Workspace
If you successfully completed the previous lab in this course, you can continue to
work in the same workspace. Otherwise you must import the projects, in Project
Lab6-Combin servlets, JSPs, and JavaBeans
1


Interchange format, into the workspace.
If you update the database and want to reinstate the original data you can
rebuild the database at any time.
Preparing a new workspace (if you are not continuing from a previous lab):
__ 1. Review the detailed steps in Appendix A to potentially delete projects, and to
import a Project Interchange zip file. This will provide the starting point for this lab.
__2. Rebuilding the database as described in Appendix B. You can repeat this
step whenever you want to reinstate the original state of the database.

Step 2 Create the StockListServlet Servlet
In this step, you will create the processRequest() method in the StockListServlet
servlet to retrieve a list of stock items. The retrieve getXXX() and setXXX() method
in the Stock class is used to retrieve the stock item list, and the list is stored in the
StockListBean you created in a previous lab. The JavaBean is made available to
the view layer components by storing it in the servlet’s session attribute.
__ 1. create the processRequest() method in StockListServlet to implement the
logic described above.
__ a. Create a Servlet named StockListServlet in onlinestockWeb and
open the it in the Java Editor..
__ b. create the entire processRequest() method and replace it with
the code fragment below
Note: in the <unpack
dir>\AdvJ2EELabs\Web\Lab6-CombineAll\code\StockListServlet.ja
va file, the full code is also available.
public class StockListServlet extends HttpServlet implements Servlet {
/*
(non-Java-doc)

* @see javax.servlet.http.HttpServlet#HttpServlet()

*/
Lab6-Combin servlets, JSPs, and JavaBeans
2



public StockListServlet() {
super();
}

/*
(non-Java-doc)

* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest arg0,
HttpServletResponse arg1)

*/

protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws
ServletException, IOException

{
doPost(arg0,arg1);
}

/*
(non-Java-doc)

* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest arg0,
HttpServletResponse arg1)

*/

protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws
ServletException,

IOException {
processRequest(arg0,arg1);
}


private void processRequest(HttpServletRequest req,



HttpServletResponse resp) throws IOException {


HttpSession session = req.getSession(false);


ServletContext context = getServletContext();
Lab6-Combin servlets, JSPs, and JavaBeans
3





StockListBean listStock = new StockListBean();
listStock.setStockList(DaoFactory.getStockDao().find());



try {
if(listStock.getStockList().size() < 1){



context.getRequestDispatcher("/stock/noListStock.jsp").forward(req,
resp);
}else{
session.setAttribute("listStock", listStock);
context.getRequestDispatcher("/stock/listStock.jsp").forward(req, resp);
}



} catch (ServletException e) {
//
System
error
-
report error 500 and message


resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"This
is
a
ServletException.");


}
}

}
__ c.
Resolve the missing import errors by clicking the light bulb icons in
the left ruler and selecting the option to import the missing classes, or by
organizing imports with CTRL+SHIF+o. You may also wish to reformat the results
by pressing CTRL-Shift-F.
__ d. Inspect to code and make sure you understand what it does. Here are
some points to note:

If the item list returned by the find() method is empty, control is forwarded to
noListStock.jsp. If the item list is populated with at least one item, a new
Lab6-Combin servlets, JSPs, and JavaBeans
4


StockListBean is created to store the list in an attribute called listStock, and control
is forwarded to listStock.jsp.

The modified processRequest() method also catches the ServletException
and IOException error thrown by the processRequest () method. The catch block
handles the ServletException error by using the error reporting method in the
HttpServletResponse class called sendError().

The sendError() method has two parameters: an int error code and a String
error message. The most appropriate error code to use in this case is 500
(server internal error), which is available as a static class variable named
SC_INTERNAL_SERVER_ERROR in the HttpServletResponse class.
__ e.Save your changes and close the StockListServlet.java editor.

__ 2.Create a new JSP file called noListStock.jsp in the WEB-INF/stock folder that
will contain no dynamic content. The page will simply report to the user that
no items have been checked out from the OnlineStock.
__ a. In the Project Explorer view, select Dynamic > Web Projects
onlinestockWeb > WebContent > WEB-INF >stock and select File > New >
JSP File from the main menu. The New JSP File dialog appears.
__ b. On the JSP File page, enter noListStock.jsp in the File Name field.
__ c. Ensure the Configure advanced options checkbox is selected.
__ d. Accept the remaining defaults and click Next.
__ e. Skip the Tag Libraries page and click Next.
__ f. On the second JSP File page, ensure that HTML Strict is selected in the
__ g. Click Finish. The noListStock.jsp JSP page is automatically opened in the

Page Designer. Ensure that the Design tab is selected.

__ 3. Modify the noListStock.jsp JSP page to add static text messages to display
to the user.
Lab6-Combin servlets, JSPs, and JavaBeans
5


__ a. In the Page Designer for noListStock.jsp, change the text “Place content
here” to “Online Stock”.
__ b. With the cursor still on the line, select Format > Paragraph > Heading 1
from the main menu.




__ c. Press the down arrow key once to move the cursor to the next line.
__ d. Enter the text “There are all Stocks”.
__ e. With the cursor still on the line, select Format > Paragraph > Heading 2
from the main menu.
__ f. Press the down arrow key once to move the cursor to the next line. __ g.
Enter the text “You currently do not have any items checked out from the stock.”.
__ h. With the cursor still on the line, select Format > Paragraph > Heading 4
from the main menu
__ i. At this point, your JSP page should match the following screen capture.
Lab6-Combin servlets, JSPs, and JavaBeans
6




__ j. Save your changes and close noListStock.jsp.

Step 3 create the listStock JSP
In the previous lab, you hardcoded a table of values in listStock.jsp that
represented data returned from the StockListBean JavaBean. You now have the
real JavaBean to work with. In this step, you will create listStock.jsp to include the
JavaBean in the JSP page using the <useBean> tag, and access the bean’s
contents using the <getProperty> tag. This modification represents a transfer of
data between the Model and View layers of the MVC design paradigm.
Recall that the list of items is passed in the JavaBean as a session attribute
named listitems. The JSP page needs to obtain the bean from the session
attribute, extract the list of items from the bean into a local List object, and then
process each item (as represented by the Stock object) in the list to construct a
row in the HTML display table.
__ 1.create listStock.jsp.
__ a. Create a new JSP file called listStock.jsp in the WEB-INF/stock folder that
will contain no dynamic content.
__ b. Copy the code of noListStock.jsp.
__ c. Delete the line of “You currently do not…”
Lab6-Combin servlets, JSPs, and JavaBeans
7


__ 2. Include the StockListBean JavaBean in the JSP page using the
<useBean> tag.
__ a. Select the empty space between the title (“OnlineStock”) and the subtitle
(“There are all stocks”) to position the cursor between them.
__ b. In the Palette view, expand the JSP Tags drawer and double-click the
Bean component. The Insert JSP Bean dialog appears.


__ c.In the Insert JSP Bean dialog, enter the following information:

— ID: listStock


Type:
Bean

— Scope: Session

— Type: edu.ynu.onlinestock.action.business.StockListBean

Lab6-Combin servlets, JSPs, and JavaBeans
8




__ d. Accept the remaining defaults and click OK. The JSP bean icon will
appear between the page titles.


__ 3. Implement the code to dynamically generate the table of checked-out items
on the JSP page using a combination of for loops and getter methods in the
Stock object.
__ a. Click the empty space between the subtitle (“There are all stocks”) and
the table to position the cursor between them.
__ b. In the Palette view, expand the JSP Tags drawer and double-click the
Scriptlet component. The JSP Scriptlet icon appears between the subtitle and
the table.
__ c. Select the JSP Scriptlet icon and switch to the Properties view. The
jsp:scriptlet tab is automatically selected.
Lab6-Combin servlets, JSPs, and JavaBeans
9




__ d.Enter the following line of code in the jsp:scriptlet text area.
for (int i=0; i < listStock.getStockList().size(); i++) {
pageContext.setAttribute("item",
listStock.getStockList(i));
}

Information: Recall that listStock is actually an alias for the JavaBean, and this
code represents a for loop that iterates over the list of items in the JavaBean’s List
object. The getStockList() method returns the List object, and the size() method
returns the number of items in the List.
In the above line of code, notice that the closing brace bracket is intentionally left
out. The closing brace bracket will be placed at the end of the table, so in each
iteration of the loop a new row of data is added to the table. Understand that JSP
scriptlets are used to add fragments of Java code; only the final Java structure
needs to be valid and compliable.
__ e. In the Palette view, double-click the Bean component in the JSP
Tags. The Insert JSP Bean dialog will appear.
__ f. In the Insert JSP Bean dialog, enter the following information.

— ID: item

— Class: edu.ynu.onlinestock.model.Stock

— Scope: Page
Lab6-Combin servlets, JSPs, and JavaBeans
10





__ g. Accept the remaining defaults and click OK. The Bean icon appears
before the first scriptlet icon between the two page titles. This bean
represents an item on loan to the stock.


__ 4.Modify the HTML table and use the <getProperty> tag to extract information
from each Stock object returned from the List in the JavaBean.
__ a. In the Page Designer, highlight the text in the first cell (Bob Coder) and
press delete to remove the text.
__ b. In the Palette view, expand the JSP Tags drawer and double-click the
Get Property component. The Insert JSP Get Property dialog appears.
__ c. In the Insert JSP Get Property dialog, select item > id from the Beans and
properties area.
Lab6-Combin servlets, JSPs, and JavaBeans
11




__ d. Click OK. The Get Property icon appears inside the first cell.
__ e. Repeat steps 4a) to 4c) for the remaining three columns, choosing the
bean properties as follows:
— Select item > companyName for the cell in the companyName column
— Select item > type for the cell in the type column
— Select item > price for the cell in the price column
— Select item > date for the cell in the date column


Lab6-Combin servlets, JSPs, and JavaBeans
12



<BODY>
<H1>Online Stock.</H1>
<H2><BR>
<jsp:useBean id="listStock"

type="edu.ynu.onlinestock.action.business.StockListBean"

scope="session"></jsp:useBean>
<jsp:useBean id="item" class="edu.ynu.onlinestock.model.Stock"

scope="page"></jsp:useBean>
<%
/*
for (int i=0; i < listStock.getStockList().size(); i++) {
pageContext.setAttribute("item",
listStock.getStockList(i));
*/
%>
There are all Stocks.</H2>
<H4><BR>


<TABLE width="100%" border="0" cellpadding="0" cellspacing="1">

<TBODY>


<TR>



<TH width="20%">id</TH>



<TH width="20%">companyName</TH>



<TH width="20%">type</TH>



<TH width="20%">price</TH>
<TH width="20%">date</TH>


</TR>


<%for (int i = 0; i < listStock.getStockList().size(); i++) {
pageContext.setAttribute("item", listStock.getStockList(i));%>



<TR>



<TD align="center"><jsp:getProperty name="item" property="id" /></TD>



<TD align="center"><jsp:getProperty name="item" property="companyName" /></TD>



<TD align="center"><jsp:getProperty name="item" property="price" /></TD>
Lab6-Combin servlets, JSPs, and JavaBeans
13





<TD align="center"><jsp:getProperty name="item" property="price" /></TD>
<TD align="center"><jsp:getProperty name="item" property="date" /></TD>


</TR>


<%}%>

</TBODY>
</TABLE>

</BODY>



__ f. At this point, listStock.jsp should match the following screen capture.
Notice that except for the page titles, almost everything else is generated
using a combination of JavaBeans and JSP tags.
Lab6-Combin servlets, JSPs, and JavaBeans
14




Step 4 Create the Error JSP
In Step 1, you coded a sendError() method in the StockListServlet servlet with a
parameter of SC_INTERNAL_SERVER_ERROR (the HttpServletResponse
class variable corresponding to error code 500) to handle the case of an
ServletException error being thrown by the processRequest() method. In this
step, you will create the custom error JSP page that reports the internal server
error to the user.
A custom error JSP page allows errors to be reported on a page that is
customized to accommodate the “look and feel” and specific needs of the
application. If the custom error JSP page did not exist, a standard server page
would display the error instead.
To make the error JSP page available for use by the application, the Web
deployment descriptor must be updated to register the JSP page as a handler for
Lab6-Combin servlets, JSPs, and JavaBeans
15


a particular code which, in this case, is 500.
__ 1.Create a new JSP named error.jsp in onlinestockWeb with the same look and
feel as the other Online Stock application pages.
__ a. In the Project Explorer view, select Dynamic > Web Projects
onlinestockWeb > WebContent > WEB-INF > stock and select File > New >
JSP File from the main menu. The New JSP File dialog appears.
__ b. On the JSP File page, enter error.jsp in the File Name field.
__ c. Ensure the Configure advanced options checkbox is selected.
__ d. Accept the remaining defaults and click Next.
__ e. Skip the Tag Libraries page and click Next.
__ f. On the second JSP File page, ensure that HTML Strict is selected in the
__ g. Click Finish. The error.jsp JSP page is automatically opened in the Page
Designer.

Lab6-Combin servlets, JSPs, and JavaBeans
16



__ 2. Modify error.jsp to add static text titles with the Online Stock look and feel.
__ a. In the Page Designer for error.jsp, change the text “Place content here”
to “Online Stock”.
__ b. With the cursor still on the line, select Format > Paragraph > Heading 1
from the main menu.
Lab6-Combin servlets, JSPs, and JavaBeans
17




__ c. Press the down arrow key once to move the cursor to the next line.
__ d. Enter the text “An error has been detected”. __ e. With the cursor still on
the line, select Format > Paragraph > Heading 2 from the main menu.

__ 3. Add a JSP Scriptlet to extract the error code and message from the request
object. The error code is contained in a request attribute named
javax.servlet.error.status_code, and the message is contained in a request
attribute named javax.servlet.error.message.
__ a. Click the empty space between the title (“Online Stock”) and the subtitle
(“An Error Has Been Detected”) to position the cursor there.
__ b. In the Palette view, expand the JSP Tags drawer and double-click the
Scriptlet component. The JSP Scriptlet icon appears at the cursor position.
__ c. In the Page Designer, select the JSP Scriptlet icon and switch to the
Properties view. The jsp:scriptlet tab is automatically selected.
__ d.In the jsp:scriptlet text area, enter the following lines of code. The first line
Lab6-Combin servlets, JSPs, and JavaBeans
18


retrieves the error code from the request attribute javax.servlet.error.status_code,
and the second line retrieves the error message from the request attribute
javax.servlet.error.message. Both lines of code store the attributes in local
variables called code and message, respectively.
Integer code = (Integer)request.getAttribute(
"javax.servlet.error.status_code");

String message =
(String) request.getAttribute("javax.servlet.error.message");




__ 4. Use JSP Expression tags to display the error code and error message to
the user below the subtitle.
__ a. Click the empty space below the subtitle to place the cursor below the subtitle.
__ b. Enter the text “Error code: “. Remember to add a space after the colon.
__ c. Press the down arrow key once to move the cursor to the next line.
Lab6-Combin servlets, JSPs, and JavaBeans
19


__ d. Enter the text “Error message: “. Remember to add a space after the colon.
__ e. Press the down arrow key once to move the cursor to the next line.
__ f. Enter the text “Please report this error to the OnlineStock Help Desk,
sinlff@163.com”.
__ g. Click the empty space beside the line “Error code: “to place the cursor at the
end of the line.
__ h. In the Palette view, double-click the Expression component. The JSP
Expression icon appears at the cursor position.
__ i. Switch to the Properties view. The jsp:expression tab is automatically selected.
__ j. Enter code in the jsp:expression text area.
__ k. Click the empty space beside the line “Error message: “to place the cursor at
the end of the line.
__ l. In the Palette view, double-click the Expression component. The JSP
Expression icon appears at the cursor position.


__ m. Switch to the Properties view. The jsp:expression tab is automatically
selected.
__ n. Enter message in the jsp:expression text area.
__o. Verify that your error.jsp JSP page matches the following screen capture.
Lab6-Combin servlets, JSPs, and JavaBeans
20





__ p. Save your changes and close the error.jsp tab.
__ 5.Update the Web Deployment Descriptor to register this error page as the
handler for the error code 500.
__ a. In the Project Explorer view, navigate to Dynamic Web Projects >
LibraryWebProject > Java Resources > JavaSource > WebContent >
WEB-INF and double-click web.xml to open the file in the xml Editor.
Lab6-Combin servlets, JSPs, and JavaBeans
21




__ b.Switch to the Pages tab and locate the Error Pages section.
Information: The Error Pages section is located in the top-right corner of the editor,
but sometimes the section heading does not appear, and only the text “response
to HTTP error codes:” appears. To resolve this problem, simply resize the
Application Developer window. The screen refreshes and the section head-ings
should appear.
Lab6-Combin servlets, JSPs, and JavaBeans
22



__ c.Under the Error Pages section, click the Add button.


__ d. Click the Select button beside the Error Code field. In the Select an Error
Code dialog that appears, choose the error code 500 (Internal Server Error)
and click OK.
Lab6-Combin servlets, JSPs, and JavaBeans
23



__ e. Click the Browse button beside the Location field. In the Location dialog
that appears, select WEB-INF > Stock > error.jsp and click OK.

__ f. Click Finish when you are returned to the Add Error Code Error Page
Lab6-Combin servlets, JSPs, and JavaBeans
24


dialog.

__ g. Save your changes to the deployment descriptor and close the tab.

Step 4 Test the JSPs and Servlets
You are now ready to test the JSPs and Servlets that you created in this and
previous exercises. At this point, you should be able to display the login page,
login with a valid patron ID and password, and see a list of checked out items.
You can login by right-clicking Dynamic Web Projects > onlinestockWeb > Java
Resources > WebContent > stock > listStock.jsp and selecting Run > Run on
Server... in the Project Explorer view. When the Server Selection dialog appears,
accept the default option to choose an existing server (WebSphere Application
Server v6.0) and click Finish. The login page appears in Web browser.
Lab6-Combin servlets, JSPs, and JavaBeans
25


The following table lists the books currently checked out by each OnlineStock .




__ 1. Perform the listStock.jsp to verify that the listStock.jsp is still working.
__ 2. If there is no stock in the database,the page will forward
noListStock.jsp and display a prompt.
Lab6-Combin servlets, JSPs, and JavaBeans
26


__ 3. If the 500 erorr or ServletException appear,the page will forward error.jsp
which display the error code and prompt.
END OF LAB

Lab6-Combin servlets, JSPs, and JavaBeans
27