5.4 Web Component Client
The MusicCart has a JSP web component client that uses the stateful MusicCart EJB and MusicIterator EJB. This JSP program is more complicated than the examples you've seen previously, so let's take time to explain its structure.
The MusicCart shopping JSP program consists of five JSP files. You've already seen error.jsp (see Listing 4.10 on page 119), so we're not going to repeat that program here. Figure 5-6 shows how the other JSP files interact.
Figure 5-6 Relationship Among JSP Files for the MusicCart JSP Web Component
The login.jsp and loginPost.jsp files allow the client to "log in" and establish a customer identity. If successful, the musicCart.jsp displays a radio button list of recording titles for one page. The screen also has buttons to add or remove recording titles in the music cart, page through the list of recording titles with Next or Previous, and display tracks from a specific recording.
The shoppingPost.jsp file is responsible for handling the shopping requests (adding and removing titles) and for displaying the track list. As the user mod-ifies the contents of the shopping cart, shoppingPost.jsp displays its new contents in HTML table format.
The musicCart.jsp uses MusicIterator EJB to page through the Music Collection database. File shoppingPost.jsp uses the MusicCart EJB to keep track of customer information and the current contents of the shopping cart. It also accesses the MusicIterator EJB to read the selected recording's track list. As you will see, most of the session data is stored in the two stateful session beans (MusicCart EJB and MusicIterator EJB), but the JSP session object also stores session data.
Design Guideline
It is always preferable to keep track of session data inside stateful session beans instead of JSP session objects. In the long run, data in stateful session beans is much easier to maintain than data in a web component.
Let's look at several screen shots that illustrate the JSP client. The initial login page (login.jsp) prompts for a name and password. After supplying this information (any string will work as long as it's not empty), the user clicks on a "Submit Login" button. The loginPost.jsp page acknowledges a successful login and provides access to the Music Collection site. Figure 5-7 shows the initial page after entering the Music Collection site.
Figure 5-7 Screen Shot After the User Successfully Logs In to the Music Collection Site
The musicCart.jsp page shows the first three recordings from the Music Collection database on the screen. There are buttons to view the tracks of a recording, add a selected recording to the music cart, or delete a recording from the cart. If a user chooses to view tracks, the screen looks similar to the display in Figure 46 on page 111. The Previous and Next buttons allow users to "page" through the recordings in the Music Collection.
With "Imagine" already selected, let's click on "Add Recording to Cart." Figure 5-8 shows the result.
Figure 5-8 Screen Shot After the User Clicks "Add Recording to Cart" for Imagine
We then return to the main page. Here we click on the "Next" button which displays the next set of recordings as shown in Figure 5-9.
Figure 5-9 Screen Shot After the User Returns to the Main Page and Clicks on the Next Button
If we select "Graceland" and attempt to delete this recording from our shopping cart, we'll see an error page, since this recording is not in our cart. Figure 5-10 shows the result.
Figure 5-10 Screen Shot After the User Attempts to Remove an Item Not Currently in the Shopping Cart
login.jsp
Listing 5.15 contains login.jsp, which presents a login screen to the user. It requests two text fields: a login name and password. A Submit button allows the user to submit the login information to the login processing program, log-inPost.jsp.
Listing 5.15 login.jsp
<%-- login.jsp --%> <%-- JSP Component to gather user name and password information. --%> <%@ page errorPage="error.jsp" %> <% String requestURI = request.getRequestURI(); session.putValue("loginURL", requestURI); %> <html> <head> <title>Music Collection Database Login Page</title> </head> <body bgcolor=white> <center> <h1>Login Page</h1> <hr> <p> Please provide the following information <form method="post" action="loginPost.jsp"> <p> <table border=2 cellpadding=5 bgcolor=#e0e0e0> <tr><td> Name: </td><td> <input TYPE="text" NAME="name" size=20> </td></tr> <tr><td> Password: </td><td> <input TYPE="password" NAME="password" size=20> </td></tr> <tr><td align=center colspan=2> <input TYPE="submit" NAME="Login" VALUE="Submit Login"> </td></tr> </table> </form> </body></html>
loginPost.jsp
Listing 5.16 contains loginPost.jsp, which receives login information submitted by the user. The customer identity is transient; that is, we don't save it to permanent store. As long as neither field is empty, the login is successful. (In the next chapter, we provide a customer name and password verification against a Customer database.) Upon successfully logging in, the program builds a CustomerVOvalue object from the input data and stores it into the session object for the musicCart.jsp program. The user also sees a congratulatory message and a link to the Music Collection page.
An unsuccessful login reports an error and displays a link back to the original login page.
<%-- loginPost.jsp --%> <%-- JSP Web component to process login information making sure user has supplied a value for each field. --%> <%@ page import="CustomerVO" errorPage="error.jsp" %> <% CustomerVO customer = null; %> <html> <title>Process Login</title> <body bgcolor=white> <center> <% String requestURI = (String)session.getValue("loginURL"); // Get name and password values provided by user String name = (String)request.getParameter("name"); String password = (String)request.getParameter("password"); // Check to make sure they're not empty if (name.equals("") || password.equals("")) { // Empty, report error to user // We use html formatting tags to create an error box // with red lettering so that it will stand out. %> <h1>Login Error</h1> <hr> <p> <p STYLE="background:#bfbfbf;color:red; font-weight:bold;border:double thin;padding:5"> You have left a field empty. You must provide both a name and a password. </font> <br><br><a href="<%= requestURI %>"> Return to Login Page</a> <% } else { customer = new CustomerVO(name, password, "NoEmail"); session.putValue("customer", customer.getName()); // a new customer requires a new music cart; // put this information in session object for // musicCart.jsp String newCustomer = "new"; session.putValue("newCustomer", newCustomer); %> <h1>Login Successful</h1> <p> <h2>Welcome <%= customer.getName() %> </h2> <hr> <p> <br><br><a href="musicCart.jsp">Enter Music Collection Site</a> <% } %> </body></html>
musicCart.jsp
Listing 5.17 contains musicCart.jsp, which manipulates the MusicCart EJB and the MusicIterator EJB on behalf of the user. The program presents a radio button list of recording titles for one page of the Music Collection database. We set the page size to a very small value (3). (We don't have many titles in our database and we want to be able to manipulate them with the Next and Previous buttons.) A user may select a title or request a different page of data. Once the user selects a title, one of three commands can be chosen: add a title to the shopping cart, remove a title from the shopping cart, or view a track list for that title. The title and the command are stored in a requestobject for the next JSP file, shop-pingPost.jsp.
Inside jspInit(), we initialize the home interfaces for both stateful session beans and store them in class variables. All clients can share these instanceswe use them to create a stateful session bean for each new customer. Note that the customerCounterinteger is also a class wide variable. We initialize it when the application server first deploys the web component. Each new customer increments the counter.
This program gets most of its variables from the session object, since the user returns to this page multiple times. The logic determines when the user is a new customer. A new customer must have a new instance of both the Music-Cart EJB and the MusicIterator EJB. A returning customer obtains these objects from the implicit session object.
Listing 5.17 musicCart.jsp
<%-- musicCart.jsp --%> <%-- JSP Web component to read the Music Collection Database using the ValueListIterator Pattern --%> <%-- The following page directive tells the JSP engine to import the named classes and packages when compiling the generated servlet code and to use "error.jsp" for an errorPage. --%> <%@ page import="MusicCart,MusicCartHome,CustomerVO,Music-Iterator, MusicIteratorHome,RecordingVO,java.util.*, javax.naming.Context, javax.naming.InitialContext, javax.rmi.PortableRemoteObject" errorPage="error.jsp" %> <%-- The following variables appear in a JSP declaration. They may be shared. --%> <%! MusicIteratorHome musicHome; MusicCartHome cartHome; int customerCounter = 0; public void jspInit() { try { Context initial = new InitialContext(); Object objref = initial.lookup( "java:comp/env/ejb/EJBMusic"); // a reference to the home interface is shareable musicHome = (MusicIteratorHome) PortableRemoteObject.narrow( objref, MusicIteratorHome.class); System.out.println( "created MusicIteratorHome object"); objref = initial.lookup( "java:comp/env/ejb/MyMusicCart"); // a reference to the home interface is shareable cartHome = (MusicCartHome) PortableRemoteObject.narrow(objref, MusicCartHome.class); } catch (Exception ex) { System.out.println("Unexpected Exception: " + ex.getMessage()); } } %> <% // Initialize variables from session object ArrayList albums = null; int total = 0; String currentTitle = (String)session.getValue("curTitle"); if (currentTitle == null) currentTitle = ""; String customer = (String)session.getValue("customer"); String newCustomer = (String)session.getValue("newCustomer"); MusicCart cart = (MusicCart)session.getValue("musicCart"); MusicIterator mymusic = (MusicIterator)session.getValue("mymusic"); if (cart == null || newCustomer.equals("new")) { // new customer; initialize music cart and // music iterator customerCounter++; System.out.println("New Session or Customer for " + customer); cart = cartHome.create(customer); mymusic = musicHome.create(); mymusic.setPageSize(3); albums = mymusic.nextPage(); newCustomer = "old"; session.putValue("newCustomer", newCustomer); currentTitle = ""; } else { // NOT a new customer; get list from session object albums = (ArrayList)session.getValue("albums"); } String requestURI = request.getRequestURI(); session.putValue("musicURL", requestURI); session.putValue("mymusic", mymusic); session.putValue("musicCart", cart); total = mymusic.getSize(); // direction indicates user wants Previous or Next page String direction = (String)request.getParameter("direction"); if (direction == null) direction = ""; // use MusicIterator to check status // and get next page if (direction.equals("Next") && mymusic.hasMoreElements()) albums = mymusic.nextPage(); // Check status and get previous page else if (direction.equals("Previous") && mymusic.hasPreviousElements()) albums = mymusic.previousPage(); // Use the current values in albums if direction does not // specify either "Previous" or "Next" // Save albums in session object session.putValue("albums", albums); %> <%-- The following html code sets up the page to display the recording titles in radio buttons and invoke page shoppingPost.jsp with the selected user input. --%> <html> <head> <title> Music Collection Database with ValueListIterator</title> </head> <body bgcolor=white> <center> <p> Customer <%= customer %> <p> You are customer number <%= customerCounter %> <p> <h1>Music Collection Database with ValueListIterator</h1> <hr> <p> There are <%= total %> recordings <form method="post" action="shoppingPost.jsp"> <p> Select Music Recording: <p> <table border=2 cellpadding=5 bgcolor=#e0e0e0> <% // Generate html radio button elements with the recording // titles stored in each RecordingVO element. String title; RecordingVO r; Iterator i = albums.iterator(); boolean checked = false; int j = 1; while (i.hasNext()) { r = (RecordingVO)i.next(); title = r.getTitle(); // "check" the radio button if the title // matches the previous selection, or if it's the // last one and we haven't checked one yet if (title.equals(currentTitle) || (j == albums.size() && !checked)) { checked = true; %> <tr><td> <input type="radio" name="title" value="<%=title%>" checked> <%= title %> </td></tr> <% } else { %> <tr><td> <input type="radio" name="title" value="<%=title%>" > <%= title %> </td></tr> <% } // end else j++; } // end while %> <%-- Provide buttons to View, Add, Delete titles Center them at the bottom of the table --%> <tr><td align=center> <input TYPE="submit" NAME="View" VALUE="View Tracks"> </td></tr> <tr><td align=center> <input TYPE="submit" NAME="Add" VALUE="Add Recording to Cart"> </td></tr> <tr><td align=center> <input TYPE="submit" NAME="Delete" VALUE="Delete Recording from Cart"> </td></tr> </table> </form> <%-- Provide buttons to view the previous or next page of recording titles --%> <form action="musicCart.jsp" method=get> <input type="submit" name="direction" value="Previous"> <input type="submit" name="direction" value="Next"> </form> <br><a href="login.jsp">Log Out</a> </body></html>
shoppingPost.jsp
Listing 5.18 contains shoppingPost.jsp. After obtaining the current values of its variables from the session object, this program performs the appropriate action. If it receives a command to view a recording's track list, the program invokes the MusicIterator EJB's getTrackList()method to build a table with the data. To add or remove a title, the program calls the MusicCart EJB's addRecording() or removeRecording() methods and redisplays the Music-Cart's current list of titles (again in table form).
When deleting a title from the shopping cart, we invoke removeRecording() in a try block to specifically check for a ShoppingException. Method removeRecording()generates this exception when the named recording title is not in the shopping cart. After processing, the user returns to the request page (musicCart.jsp).
Listing 5.18 shoppingPost.jsp
<%-- shoppingPost.jsp --%> <%-- Use a page directive to import needed classes and packages for compilation. Specify "error.jsp" as the page's errorPage. --%> <%@ page import="ShoppingException,MusicCart, MusicCartHome,CustomerVO,MusicIterator, MusicIteratorHome,RecordingVO,TrackVO,java.util.*, javax.naming.Context, javax.naming.InitialContext, javax.rmi.PortableRemoteObject" errorPage="error.jsp" %> <%-- Declare and initialize variables. --%> <% ArrayList tracks; ArrayList shoppingList; String requestURI = (String)session.getValue("musicURL"); MusicIterator mymusic = (MusicIterator)session.getValue("mymusic"); MusicCart cart = (MusicCart)session.getValue("musicCart"); ArrayList albums = (ArrayList)session.getValue("albums"); String currentTitle = request.getParameter("title"); session.putValue("curTitle", currentTitle); %> <html> <head> <title><%= currentTitle %></title> </head> <body bgcolor=white> <center> <h1>Music Collection Database Using EJB & JSP</h1> <hr> <p> <% // Access the albums ArrayList to find the RecordingVO // object with the selected title. RecordingVO r = null; Iterator i = albums.iterator(); boolean found = false; while (i.hasNext()) { r = (RecordingVO)i.next(); if (r.getTitle().equals(currentTitle)) { found = true; break; } } if (found) { // found title String command = request.getParameter("View"); if (command != null) { // command is View tracks = mymusic.getTrackList(r); %> <table bgcolor=#e0e0e0 border=2 cellpadding=5> <p> Processing <%= command %> for <%= currentTitle %> <p> <tr> <th>Track Number</th> <th>Track Length</th> <th>Track Title</th> </tr> <% // Use a combination of scriptlet code, // html and JSP expressions to build the table TrackVO t; i = tracks.iterator(); while (i.hasNext()) { t = (TrackVO)i.next(); %> <tr> <td> <%= t.getTrackNumber() %></td> <td> <%= t.getTrackLength() %></td> <td> <%= t.getTitle() %></td> </tr> <% } out.println("</table>"); } else { command = request.getParameter("Add"); if (command != null) { // command is Add cart.addRecording(r); } else { command = request.getParameter("Delete"); if (command != null) { // command is Delete try { cart.removeRecording(r); } catch(ShoppingException ex) { // begin catch handler %> <p> Shopping Error <hr> <p> <p STYLE="background:#bfbfbf;color:red; font-weight:bold;border:double thin;padding:5"> Title <%= currentTitle %> is not currently in your shopping cart. </font> <% } // end catch handler } } // put displaylist code here %> <table bgcolor=#e0e0e0 border=2 cellpadding=5> <p> Processing <%= command %> for <%= currentTitle %> <p> <tr> <th>Current Shopping List</th> </tr> <% // Use a combination of scriptlet code, // html and JSP expressions to build the table shoppingList = cart.getShoppingList(); i = shoppingList.iterator(); while (i.hasNext()) { r = (RecordingVO)i.next(); %> <tr><td> <%= r.getTitle() %></td></tr> <% } // end while loop out.println("</table>"); } } else { out.println("No tracks for " + currentTitle + " found.<br>"); } %> <br><br><a href="<%= requestURI %>">Return to Main Page</a> </body> </html>
Deployment Descriptor
Listing 5.19 contains the deployment descriptor for our web component client. We've specified login in <servlet-name>to match login.jsp in <jsp-file>. Note there are two <ejb-ref> definitions in this descriptor file: one for the MusicIterator EJB and one for the MusicCart EJB. The <ejb-ref-name> for each EJB must match the coded name provided to the lookup() method in musicCart.jsp (see page 175).
Listing 5.19 Web Component Deployment Descriptor
<web-app> <display-name>MusicWAR</display-name> <servlet> <servlet-name>login</servlet-name> <display-name>login</display-name> <jsp-file>/login.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config>
<ejb-ref> <ejb-ref-name>ejb/EJBMusic</ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <home>MusicIteratorHome</home> <remote>MusicIterator</remote> </ejb-ref> <ejb-ref> <ejb-ref-name>ejb/MyMusicCart</ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <home>MusicCartHome</home> <remote>MusicCart</remote> </ejb-ref> </web-app>