Mastering Enterprise JavaBeans™ and the Java 2 Platform, Enterprise Edition - Roman E
..pdf
J2EE in the Real World: Combining Servlets with Enterprise JavaBeans 
461
Figure 15.1 The login screen.
Once the user has been authenticated and his or her Quote has been created, we direct the user to the next servlet—the Web Storefront.
For clarity, this chapter’s servlets perform a great deal of string concatenation when writing HTML. Each concatenation results in an expensive method call. In a perfor- mance-intensive deployment, you’d want to use a StringBuffer instead, as follows:
StringBuffer buf = new StringBuffer();
buf.append("<html>");
buf.append("<head>...
...
out.println(buf.toString());
The Web Storefront Servlet
Once the user gets through the Login servlet, he or she will be redirected to the Web Storefront (WebStorefrontServlet.java), which is the main page for our store. Our Web Storefront is quite simple, and it is shown in Source 15.2.
Notice that we have no init() method to initialize the servlet when it’s first loaded into memory. This is because there’s no state initialization that our servlets need when they’re processing service calls from the client.
Go back to the first page for a quick link to buy this book online!
462 
M A S T E R I N G E N T E R P R I S E J A V A B E A N S
package com.wiley.compBooks.ecommerce;
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
/**
* This servlet displays the main page for our
*e-commerce site.
*By the time this servlet is called, the user has
*logged in (via the Login servlet) and has a shopping
*cart started (i.e., Quote bean). Because this servlet
*is pooled and reused for different user requests,
*the servlet code does not store any information
*specific to any user. Rather, we store a reference
*to the user's Quote in the user's HttpSession object,
*which is globally accessible to all servlets.
*/
public class WebStorefrontServlet extends HttpServlet {
/**
* Called by servlet engine to service a request */
public void service (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
/*
*Get the user's session, and from that get the
*user's current quote.
*/
HttpSession session = request.getSession(false); if (session == null) {
/*
*Redirect user to login page if
*there's no session.
*/
response.sendRedirect(response.encodeUrl("/servlet/login"));
return;
}
Object obj = session.getValue("quote"); if (obj == null) {
/*
*Redirect user to login page if
*there's no session.
*/
Source 15.2 WebStorefrontServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
J2EE in the Real World: Combining Servlets with Enterprise JavaBeans 
463
response.sendRedirect(response.encodeUrl("/servlet/login"));
return;
}
Quote quote = (Quote) obj;
/*
*Now, we write the response. Set content-type
*header, indicating that we will be writing in
*HTML.
*/
response.setContentType("text/html"); PrintWriter out = response.getWriter();
/*
*Then write the data of the response. Start
*with the header.
*/
out.println( "<html>" +
"<head><title>Jasmine Computer Parts, Inc.</title></head>" +
"<body bgcolor=\"#FFFFFF\">" + "<center>" +
"<hr> <br> " + "<h1>" +
"<font size=\"+3\" color=\"red\">Jasmine's </font> " + "<font size=\"+3\" color=\"purple\">Computer </font> " + "<font size=\"+3\" color=\"green\">Parts </font>" + "</h1>" +
"</center>" +
"<br> <hr> <br> ");
/*
* Write the main body of our Web page */
out.println(
"<table border=0 cellspacing=5 cellpadding=5>" + "<tr>" +
"<td valign=\"TOP\" bgcolor=\"#FFFFAA\">" + "<p><font size=\"+1\"><a href=\"" + response.encodeUrl("/servlet/catalog") + "\">Catalog</a></font><br>" +
"Choose from our excellent selection of computer parts." +
"<p><font size=\"+1\"><a href=\"" + response.encodeUrl("/servlet/showquote") + "\">Shopping Cart</a></font><br>" +
"Look at your shopping cart to see the equipment " +
Source 15.2 WebStorefrontServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
464 
M A S T E R I N G E N T E R P R I S E J A V A B E A N S
"you've chosen" +
"</td>" + "</tr>" + "</table>" +
"<br> " + "<br> " + "<br> " + "<center><em>" +
"Based on the Java Tutorial Servlet," + "Copyright © 1998 Sun Microsystems, Inc." + "</em></center>" +
"</body>" + "</html>"); out.close();
}
public String getServletInfo() {
return "The WebStorefront servlet returns the main web page " + "for Jasmine's Computer Parts.";
}
}
Source 15.2 WebStorefrontServlet.java (continued).
When the user connects, we first check to see if he or she has a current Quote going, by extracting the Quote from the user’s servlet session. If the user has no Quote, we redirect the user back to the Login screen for authentication. Otherwise, we simply print out the main storefront page, which contains links to other servlets. The Web Storefront screen is shown in Figure 15.2.
The Online Catalog Servlet
To start adding products to his or her Quote, the user can browse the list of products available by going to the catalog Web page, which is a Java servlet, CatalogServlet.java, shown in Source 15.3. From the catalog, the user can add products to his or her Quote. He or she can also view details of a particular product, in which case the Catalog servlet will direct the user to the Product Detail servlet, described later.
Like the Web Storefront, our Catalog servlet will kick the user back to the Login servlet if he or she has no Quote going. Otherwise, the Catalog prints out the current list of products available. The Catalog screen is shown in Figure 15.3.
Go back to the first page for a quick link to buy this book online!
J2EE in the Real World: Combining Servlets with Enterprise JavaBeans 
465
Figure 15.2 The Web Storefront screen.
package com.wiley.compBooks.ecommerce;
import java.io.*; import java.util.*; import javax.servlet.*;
import javax.servlet.http.*;
/**
*This servlet displays a catalog of products to
*the end user.
*
*By the time this servlet is called, the user has
*logged in (via the Login servlet) and has a shopping
*cart started (i.e., Quote bean). Because this servlet is
*pooled and reused for different user requests, the
*servlet code does not store any information specific to
*any user. Rather, we store a reference to the user's
*Quote in the user's HttpSession object, which is
*globally accessible to all servlets.
*/
Source 15.3 CatalogServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
466 
M A S T E R I N G E N T E R P R I S E J A V A B E A N S
public class CatalogServlet extends HttpServlet {
/**
*The servlet engine calls this method when the user's
*desktop browser sends an HTTP GET request.
*/
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
*Get the user's HttpSession, and from that get
*the user's current quote.
*/
HttpSession session = request.getSession(false); if (session == null) {
/*
*Redirect user to login page if he
*doesn't have a session.
*/
response.sendRedirect(response.encodeUrl("/servlet/login"));
return;
}
Object obj = session.getValue("quote"); if (obj == null) {
/*
*Redirect user to login page if he
*doesn't have a session.
*/
response.sendRedirect(response.encodeUrl("/servlet/login"));
return;
}
Quote quote = (Quote) obj;
/*
*Now, we write the response. Set content-type
*header, indicating that we will be writing in HTML.
*/
response.setContentType("text/html"); PrintWriter out = response.getWriter();
/*
* Then write the response. Start with the header. */
out.println( "<html>" +
"<head><title> Computer Catalog </title></head>" +
Source 15.3 CatalogServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
J2EE in the Real World: Combining Servlets with Enterprise JavaBeans 
467
"<body bgcolor=\"#ffffff\">" + "<center>" +
"<hr> <br> " + "<h1>" +
"<font size=\"+3\" color=\"red\">Jasmine's </font>" + "<font size=\"+3\" color=\"purple\">Computer </font>" + "<font size=\"+3\" color=\"green\">Parts</font>" + "</h1>" +
"</center>" +
"<br> <hr> <br> ");
/*
*Get our ProductBase servlet that contains
*all the available products.
*/
ProductBaseServlet productBase = (ProductBaseServlet) getServletConfig().getServletContext().getServlet("productbase");
/*
*If user wants to purchase something (via
*the URL parameter 'Buy'), add the desired
*product to the quote.
*/
String productIDToAdd = request.getParameter("Buy"); if (productIDToAdd != null) {
/*
* Convert the product ID into a Product. */
Product product = null; try {
product = productBase.getProduct(productIDToAdd);
}
catch (Exception e) {
throw new ServletException(e.toString());
}
/*
* Add the product to the quote */
quote.addProduct(product);
out.println( "<p><h3>" +
"<font color=\"#ff0000\">" +
"<i>" + product.getName() + "</i> "+
"has been added to your quote.</font></h3>");
}
Source 15.3 CatalogServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
468 
M A S T E R I N G E N T E R P R I S E J A V A B E A N S
/*
*Give the option of viewing the current quote.
*Also give option to purchase the selections
*made.
*/
out.println(
"<a href=\"" + response.encodeUrl("/servlet/showquote") + "\"> View Current Quote</a></th>");
/*
* Show the catalog */
out.println(
"<br> " +
"<h3>Please choose from our selections</h3>" + "<center> <table>");
/*
* Print out info on each product in the catalog */
Vector products = productBase.getAllProducts(); for(int i=0; i < products.size(); i++) {
Product prod = (Product) products.elementAt(i);
String productID = ((ProductPK)prod.getPrimaryKey()).productID;
out.println( "<tr>" +
"<td bgcolor=\"#ffffaa\">" + "<a href=\"" +
response.encodeUrl("/servlet/productdetails" + "?productID=" + productID) +
"\"> <strong>" + prod.getName() + " </strong></a>" +
"</td>" +
"<td bgcolor=\"#ffffaa\">" +
"$" + prod.getBasePrice() + "  " + "</td>" +
"<td bgcolor=\"#ffffaa\">" + "<a href=\"" +
response.encodeUrl("/servlet/catalog?Buy=" + productID) + "\"> Add to Quote </a>" +
"</td>" + "</tr>");
}
Source 15.3 CatalogServlet.java (continues).
Go back to the first page for a quick link to buy this book online!
J2EE in the Real World: Combining Servlets with Enterprise JavaBeans 
469
out.println("</table></center></body></html>");
out.close();
}
public String getServletInfo() {
return "The Catalog servlet adds products to the user's " + "quote and prints the catalog.";
}
}
Source 15.3 CatalogServlet.java (continued).
The Catalog servlet gets its list of products via a different servlet, the Product Base servlet (described later). We cache the list of products in the Product Base servlet for efficiency. Our catalog prints out a URL link to add each product to the user’s current shopping cart (Quote). If the user clicks on the link, the Web browser will return the Product ID to the Catalog servlet as a URL parameter. When the Catalog servlet is called with a Product ID, the servlet first extracts the ID from the request. It then uses the Product Base servlet to convert the
Figure 15.3 The Catalog screen.
Go back to the first page for a quick link to buy this book online!
470 
M A S T E R I N G E N T E R P R I S E J A V A B E A N S
Figure 15.4 Adding a Product to the Quote.
Product ID into a real Product EJB object. Finally, the Catalog servlet then adds the Product EJB object to the user’s current Quote. Adding a Product is shown in Figure 15.4.
The user can also navigate to several other servlets from the catalog, such as the Product Detail servlet for viewing the details of a particular product. In this case, the product ID to be viewed is passed as a parameter to that servlet.
The Product Base Servlet
Many of our servlets need to work with Product entity beans. It would be very inefficient, though, to have each servlet communicate across the tier boundary every time a Product needed to be found. Therefore, we cache our entire product line in a Product Base servlet. The Product Base servlet never interacts directly with the user. It’s simply a servlet that other servlets can call when they need to retrieve Products. The code is in ProductBaseServlet.java, shown in Source 15.4.
Our Product Base servlet is responsible for holding all the Product EJB objects that exist. Therefore, it needs to look them all up in its init() method. init() performs JNDI initialization, locates the Product home object, and then finds
Go back to the first page for a quick link to buy this book online!
