Home > Articles

This chapter is from the book

Building the Project

The following section discusses the files that make up the application, starting with the deployment descriptor and continuing with the controller servlet. The section then discusses each of the JSP pages and other classes in detail.

The Deployment Descriptor

One of the files included in the Burnaby directory is the deployment descriptor (web.xml). This file can be found in the WEB-INF directory. In this web.xml file, you specify several initial parameters that will become global variables in the servlet/JSP pages. These global variables are loaded into the ServletContext object when the servlet is initialized. The deployment descriptor is given in Listing 18.1.

Listing 18.1 Web.xml File

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 <!–– Define the controller servlet ––>
 <servlet>
  <servlet-name>ControllerServlet</servlet-name>
  <servlet-class>ControllerServlet</servlet-class>

  <!–– Define initial parameters that will be loaded into 
    the ServletContext object in the controller servlet —>
  <init-param>
   <param-name>base</param-name>
   <param-value>
 http://localhost:8080/burnaby/servlet/ControllerServlet</param-value>
  </init-param>
  <init-param>
   <param-name>jdbcDriver</param-name>
   <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
  </init-param>
  <init-param>
   <param-name>imageUrl</param-name>
   <param-value>http://localhost:8080/burnaby/images/</param-value>
  </init-param>
  <init-param>
   <param-name>dbUrl</param-name>
   <param-value>jdbc:odbc:Burnaby</param-value>
  </init-param>
  <init-param>
   <param-name>dbUserName</param-name>
   <param-value></param-value>
  </init-param>
  <init-param>
   <param-name>dbPassword</param-name>
   <param-value></param-value>
  </init-param>
 </servlet>
</web-app>

The following list describes each initial parameter:

  • base. The URL of the controller servlet that will be used in the HREF attribute of a hyperlink or the ACTION attribute of an HTML form in the JSP pages. For example, base will have the following value if you are using Tomcat on the local machine on port 8080:
    	http://localhost:8080/burnaby/servlet/ControllerServlet

    When deploying the application, replace "localhost:8080" with your domain name.

  • jdbcDriver. The JDBC driver used to access the database.

  • imageUrl. The URL where images are located.

  • dbUrl. The database URL used when opening a java.sql.Connection object.

  • dbUserName. The username used when opening a java.sql.Connection object.

  • dbPassword. The password used when opening a java.sql.Connection object.

The Controller Servlet

The controller servlet is contained in the ControllerServlet.java file in the burnaby/src directory and is given in Listing 18.2.

Listing 18.2 ControllerServlet

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.brainysoftware.burnaby.DbBean;

public class ControllerServlet extends HttpServlet {

 /**Initialize global variables*/
 public void init(ServletConfig config) throws ServletException {

  System.out.println("initializing controller servlet.");

  ServletContext context = config.getServletContext();
  context.setAttribute("base", config.getInitParameter("base"));
  context.setAttribute("imageUrl", config.getInitParameter("imageUrl"));

  // instantiating the DbBean
  DbBean dbBean = new DbBean();
  // initialize the DbBean's fields
  dbBean.setDbUrl(config.getInitParameter("dbUrl"));
  dbBean.setDbUserName(config.getInitParameter("dbUserName"));
  dbBean.setDbPassword(config.getInitParameter("dbPassword"));

  // put the bean in the servlet context 
  // the bean will be accessed from JSP pages
  context.setAttribute("dbBean", dbBean);  

  try {
   // loading the database JDBC driver
   Class.forName(config.getInitParameter("jdbcDriver"));
  }
  catch (ClassNotFoundException e) {
   System.out.println(e.toString());
  }
  super.init(config);
 }


 /**Process the HTTP Get request*/
 public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
  doPost(request, response);
 }

 /**Process the HTTP Post request*/
 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

  String base = "/jsp/";
  String url = base + "Default.jsp";
  String action = request.getParameter("action");

  if (action!=null) {
   if (action.equals("search"))
    url = base + "SearchResults.jsp";
   else if (action.equals("browseCatalog"))
    url = base + "BrowseCatalog.jsp";
   else if (action.equals("productDetails"))
    url = base + "ProductDetails.jsp";
   else if (action.equals("productDetails"))
    url = base + "ProductDetails.jsp";
   else if (action.equals("addShoppingItem") ||
    action.equals("updateShoppingItem") ||
    action.equals("deleteShoppingItem") ||
    action.equals("displayShoppingCart"))
    url = base + "ShoppingCart.jsp";
   else if (action.equals("checkOut"))
    url = base + "CheckOut.jsp";
   else if (action.equals("order"))
    url = base + "Order.jsp";
  }
  RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(url);
  requestDispatcher.forward(request, response);

 }
}

As you can see from Listing 18.2, the two important methods are init and doPost. The init method does the following things:

  • Reads initial parameters from the deployment descriptor and initializes global variables for the whole application, as follows:

      ServletContext context = config.getServletContext();
      context.setAttribute("base", config.getInitParameter("base"));
      context.setAttribute("imageUrl", config.getInitParameter("imageUrl"));
  • Instantiates the DbBean JavaBean and puts it in the servlet context object:

    // instantiating the DbBean
      DbBean dbBean = new DbBean();
      // initialize the DbBean's fields
      dbBean.setDbUrl(config.getInitParameter("dbUrl"));
      dbBean.setDbUserName(config.getInitParameter("dbUserName"));
      dbBean.setDbPassword(config.getInitParameter("dbPassword"));
    
      // put the bean in the servlet context 
      // the bean will be accessed from JSP pages
      context.setAttribute("dbBean", dbBean);  

    This bean can be accessed from the JSP pages using the following useBean tag.

    <jsp:useBean id="dbBean" scope="application" 
    class="com.brainysoftware.burnaby.DbBean"/>
  • Loads the JDBC driver for the database, as follows:

    try {
       // loading the database JDBC driver
       Class.forName(config.getInitParameter("jdbcDriver"));
      }
      catch (ClassNotFoundException e) {
       System.out.println(e.toString());
      }

The doPost method controls the application by forwarding requests to corresponding JSP pages based on the value of the action parameter. Requests are forwarded to JSP pages using the forward method of the RequestDispatcher object, as follows:

 RequestDispatcher requestDispatcher = 
  getServletContext().getRequestDispatcher(url);
 requestDispatcher.forward(request, response);

Supporting Classes

Two supporting classes are used for this project. The first one is the Product class that represents a product in the shopping application. The second one, the ShoppingItem class, represents a shopping item. Both classes are similar except that the Product class does not have a quantity field.

The Product class and the ShoppingItem class are given in Listings 18.3 and 18.4, respectively.

Listing 18.3 Product.java

package com.brainysoftware.burnaby;

public class Product {
 public int id;
 public String name;
 public String description;
 public double price;
}

Listing 18.4 ShoppingItem.java

package com.brainysoftware.burnaby;

public class ShoppingItem {
 public int productId;
 public String name;
 public String description;
 public double price;
 public int quantity;
}

Included Files

Every JSP page has the same design—the header and the menu on the left of the page. The header is represented by the Header.jsp file, and the menu by the Menu.jsp file. These files are given in Listings 18.5 and 18.6, respectively.

Listing 18.5 Header.jsp

<%
 String base = (String) application.getAttribute("base");
 String imageUrl = (String) application.getAttribute("imageUrl");
%>

<TABLE WIDTH="740" CELLPADDING="0"
 HEIGHT="75" CELLSPACING="0" BORDER="0">
<TR>
 <TD ALIGN="left" BGCOLOR="F6F6F6">
  <FONT FACE="Verdana" SIZE="4">Burnaby e-Mall</FONT>
 </TD>
 <TD ALIGN="RIGHT" BGCOLOR="F6F6F6">
  <A HREF="<%=base%>?action=displayShoppingCart"><IMG 
   BORDER="0" SRC="<%=(imageUrl + "cart.gif")%>"></A>
  &nbsp;&nbsp;&nbsp;
 </TD>
</TR>
</TABLE>

The first four lines of the code obtain the base and imageUrl attributes from the ServletContext object, which in a JSP page is represented by the application implicit, as you see here:

<%
 String base = (String) application.getAttribute("base");
 String imageUrl = (String) application.getAttribute("imageUrl");
%>

The base and imageUrl variables are used to compose the link to the shopping cart, as follows:

<A HREF="<%=base%>?action=displayShoppingCart"><IMG 
 BORDER="0" SRC="<%=(imageUrl + "cart.gif")%>"></A>

Listing 18.6 Menu.jsp

<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>
<%
 String base = (String) application.getAttribute("base");
%>
<TABLE CELLSPACING="0" CELLPADDING="5" WIDTH="150" BORDER="0">
<TR>
 <TD BGCOLOR="F6F6F6">
  <FONT FACE="Verdana">Search</FONT>
  <FORM>
  <INPUT TYPE="HIDDEN" NAME="action" VALUE="search">
  <INPUT TYPE="TEXT" NAME="keyword" SIZE="10">
  <INPUT type="SUBMIT" VALUE="Go">
  </FORM>
 </TD>
</TR>
<TR>
 <TD BGCOLOR="F6F6F6"><FONT FACE="Verdana">Categories:</FONT></TD>
</TR>
<TR VALIGN="TOP">
 <TD BGCOLOR="F6F6F6">
<%
 Hashtable categories = dbBean.getCategories();
 Enumeration categoryIds = categories.keys();
 while (categoryIds.hasMoreElements()) {
  Object categoryId = categoryIds.nextElement();
  out.println("<A HREF=" + base + "?action=browseCatalog&categoryId=" +
   categoryId.toString() + ">" +
   categories.get(categoryId) +
   "</A><BR>");
 }
%>
 </TD>
</TR>
</TABLE>

The Menu.jsp page includes a form that allows the user to search for certain products. The form also retrieves all records from the Categories table and displays them as clickable links to the BrowseCatalog page. Retrieving the categories is done through a bean whose class is com.brainysoftware.burnaby.DbBean. This bean has an application scope shown here:

<jsp:useBean id="dbBean" scope="application"
 class="com.brainysoftware.burnaby.DbBean"/>

The Default Page

The main page of this application is the Default.jsp page. Any request that does not carry an action parameter or any request whose "action" parameter's value is invalid will be forwarded to this page. This page simply displays a welcome message that is given in Listing 18.7.

Listing 18.7 Default.jsp

<HTML>
<HEAD>
<TITLE>Welcome</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">

  <H2>Welcome to Burnaby E-Mall.</H2>

 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The SearchResults Page

The Menu.jsp page contains a search form and a number of hyperlinks to enable catalog browsing. When submitted, the search form will be forwarded to the SearchResults.jsp page, presented in Listing 18.8.

Listing 18.8 SearchResults.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application"
 class="com.brainysoftware.burnaby.DbBean"/>
<%
 String base = (String) application.getAttribute("base");
%>
 <HTML>
<HEAD>
<TITLE>Search Results</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
<%
 String keyword = request.getParameter("keyword");
 if (keyword!=null && !keyword.trim().equals("")) {
%>
  <TABLE>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Description</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Details</B></FONT></TD>
  </TR>
<%
  ArrayList products = dbBean.getSearchResults(keyword);
  Iterator iterator = products.iterator();
  while (iterator.hasNext()) {
   Product product = (Product) iterator.next();
%>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.name%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.description%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.price%></FONT></TD>
   <TD><A HREF="<%=base%>?action=productDetails&productId=<%=product.id%>">
    <FONT FACE="Verdana" SIZE="2">Details</FONT></A></TD>
  </TR>
<%
  }
 }
 else
  out.println("Please enter a search keyword.");


%>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

Note that the search keyword is contained in the "keyword" parameter.

The BrowseCatalog Page

When the user clicks one of the category hyperlinks on the menu, all products in that category are displayed by the BrowseCatalog.jsp page. This JSP page is similar to the SearchResults.jsp page, except that it accepts a "categoryId" parameter instead of "keyword."

The BrowseCatalog.jsp page is given in Listing 18.9.

Listing 18.9 BrowseCatalog.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>
<%
 String base = (String) application.getAttribute("base");
%>
<HTML>
<HEAD>
<TITLE>Browse Catalog</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
<%
 String categoryId = request.getParameter("categoryId");
 if (categoryId!=null && !categoryId.trim().equals("")) {
%>
  <TABLE>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Description</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Details</B></FONT></TD>
  </TR>
<%
  ArrayList products = dbBean.getProductsInCategory(categoryId);
  Iterator iterator = products.iterator();
  while (iterator.hasNext()) {
   Product product = (Product) iterator.next();
%>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.name%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.description%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=product.price%></FONT></TD>
   <TD><A HREF="<%=base%>?action=productDetails&productId=<%=product.id%>">
    <FONT FACE="Verdana" SIZE="2">Details</FONT></A></TD>
  </TR>
<%
  }
 }
 else
  out.println("Invalid category.");
%>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The ProductDetails Page

From the SearchResults page or the BrowseCatalog page, the user can click the Details hyperlink to display a product's details. A product's details are processed by the ProductDetails.jsp page, and from this page, the user can click the Add to Cart link to add the product to the shopping cart. The ProductDetails.jsp page is given in Listing 18.10.

Listing 18.10 ProductDetails.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>
<%
 String base = (String) application.getAttribute("base");
 String imageUrl = (String) application.getAttribute("imageUrl");
%>
<HTML>
<HEAD>
<TITLE>Product Details</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
<%
 try {
  int productId = Integer.parseInt(request.getParameter("productId"));
  Product product = dbBean.getProductDetails(productId);
  if (product!=null) {
%>
<TABLE>
<TR>
 <TD><IMG BORDER="0" WIDTH="100" SRC="<%=(imageUrl + product.id)%>.gif"></TD>
 <TD><B><%=product.name%></B><BR>
   <%=product.description%><BR>
   Price : $<%=product.price%></TD>
</TR>
<TR>
 <TD COLSPAN="2" ALIGN="RIGHT">
  <A HREF="<%=base%>?action=addShoppingItem&productId=<%=product.id%>">
   Add To Cart</A>
 </TD>
</TR>
</TABLE>
<%
  }
 }
 catch (Exception e) {
  out.println("Error: Invalid product identifier.");
 }
%>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The ShoppingCart.jsp Page

The shopping cart in this application is session based. Each shopping item is represented by the ShoppingItem class and stored in a Hashtable object called shoppingCart. This Hashtable object is stored in the Session object of each particular user.

The ShoppingCart.jsp is given in Listing 18.11.

Listing 18.11 ShoppingCart.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>
<%@ page import="com.brainysoftware.burnaby.ShoppingItem" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>
<%
 String base = (String) application.getAttribute("base");
 Hashtable shoppingCart = (Hashtable) session.getAttribute("shoppingCart");
 if (shoppingCart==null)
  shoppingCart = new Hashtable(10);

 String action = request.getParameter("action");
 if (action!=null && action.equals("addShoppingItem")) {
  try {
   int productId = Integer.parseInt(request.getParameter("productId"));
   Product product = dbBean.getProductDetails(productId);
   if (product!=null) {
    ShoppingItem item = new ShoppingItem();
    item.productId = productId;
    item.quantity = 1;
    item.price = product.price;
    item.name = product.name;
    item.description = product.description;

    shoppingCart.remove(Integer.toString(productId));
    shoppingCart.put(Integer.toString(productId), item);
    session.setAttribute("shoppingCart", shoppingCart);
   }
  }
  catch (Exception e) {
   out.println("Error adding the selected product to the shopping cart");
  }
 }

 if (action!=null && action.equals("updateShoppingItem")) {
  try {
   int productId = Integer.parseInt(request.getParameter("productId"));
   int quantity = Integer.parseInt(request.getParameter("quantity"));
   ShoppingItem item = (ShoppingItem) shoppingCart.get(Integer.toString(productId));
   if (item!=null) {
    item.quantity = quantity;
   }
  }
  catch (Exception e) {
   out.println("Error updating shopping cart");
  }
 }

 if (action!=null && action.equals("deleteShoppingItem")) {
  try {
   int productId = Integer.parseInt(request.getParameter("productId"));
   shoppingCart.remove(Integer.toString(productId));
  }
  catch (Exception e) {
   out.println("Error deleting the selected item from the shopping cart");
  }
 }

%>
<HTML>
<HEAD>
<TITLE>Shopping Cart</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
<%
%>
  <TABLE>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Description</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Quantity</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Subtotal</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Update</B></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="3"><B>Delete</B></FONT></TD>
  </TR>
<%

  Enumeration enum = shoppingCart.elements();
  while (enum.hasMoreElements()) {
   ShoppingItem item = (ShoppingItem) enum.nextElement();
%>
  <TR>
   <TD><FONT FACE="Verdana" SIZE="2"><%=item.name%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=item.description%></FONT></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=item.price%></FONT></TD>
   <FORM>
   <INPUT TYPE="HIDDEN" NAME="action" VALUE="updateShoppingItem">
   <INPUT TYPE="HIDDEN" NAME="productId" VALUE="<%=item.productId%>">
   <TD><INPUT TYPE="TEXT" Size="2" NAME="quantity" VALUE="<%=item.quantity%>"></TD>
   <TD><FONT FACE="Verdana" SIZE="2"><%=item.quantity*item.price%></FONT></TD>
   <TD><INPUT TYPE="SUBMIT" VALUE="Update"></TD>
   </FORM>
   <FORM>
   <INPUT TYPE="HIDDEN" NAME="action" VALUE="deleteShoppingItem">
   <INPUT TYPE="HIDDEN" NAME="productId" VALUE="<%=item.productId%>">
   <TD><INPUT TYPE="SUBMIT" VALUE="Delete"></TD>
   </FORM>
  </TR>
<%
  }
%>
  <TR>
   <TD COLSPAN="7"><A HREF="<%=base%>?action=checkOut">Check Out</A></TD>
  </TR>
  </TABLE>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The CheckOut Page

When users are finished shopping, they need to check out. This is done by confirming the purchase and filling in an HTML form in the CheckOut.jsp page. The Checkout page is given in Listing 18.12 and is basically a very simple HTML form on which users fill in the delivery and credit card details.

Listing 18.12 CheckOut.jsp

<%
 String base = (String) application.getAttribute("base");
%>
<HTML>
<HEAD>
<TITLE>Check Out</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
  <FORM>
  <INPUT TYPE="HIDDEN" NAME="action" VALUE="order">
  <TABLE>
  <TR>
   <TD COLSPAN="2"><I><B>Delivery Details</B></I></TD>
  </TR>
  <TR>
   <TD>Contact Name:</TD>
   <TD><INPUT TYPE="TEXT" NAME="contactName"></TD>
  </TR>
  <TR>
   <TD>Delivery Address:</TD>
   <TD><INPUT TYPE="TEXT" NAME="deliveryAddress"</TD>
  </TR>
  <TR>
   <TD COLSPAN="2"><I><B>Credit Card Details</B></I></TD>
  </TR>
  <TR>
   <TD>Name on Credit Card:</TD>
   <TD><INPUT TYPE="TEXT" NAME="ccName"</TD>
  </TR>
  <TR>
   <TD>Credit Card Number:</TD>
   <TD><INPUT TYPE="TEXT" NAME="ccNumber"></TD>
  </TR>
  <TR>
   <TD>Credit Card Expiry Date:</TD>
   <TD><INPUT TYPE="TEXT" NAME="ccExpiryDate"</TD>
  </TR>
  <TR>
   <TD>&nbsp;</TD>
   <TD><INPUT TYPE="SUBMIT" VALUE="Check Out"></TD>
  </TR>
  </TABLE>
  </FORM>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The Order Page

When the user submits the form on the CheckOut page, the request will go to the Order page. This page inserts a record into the Orders table and inserts each shopping item into the OrderDetails table. The Order.jsp page is presented in Listing 18.3.

Listing 18.13 Order.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>
<HTML>
<HEAD>
<TITLE>Order</TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
 <TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>
</TR>
<TR>
 <TD><jsp:include page="Menu.jsp" flush="true"/></TD>
 <TD VALIGN="TOP">
<%
 if (dbBean.insertOrder(request.getParameter("contactName"),
  request.getParameter("deliveryAddress"),
  request.getParameter("ccName"),
  request.getParameter("ccNumber"),
  request.getParameter("ccExpiryDate"),
  (Hashtable) session.getAttribute("shoppingCart"))) {

  session.invalidate();
  out.println("Thank you for your purchase");
 }
 else
  out.println("Error");
%>
 </TD>
</TR>
</TABLE>
</BODY>
</HTML>

The DbBean JavaBean

All the JSP pages are kept as presentation pages wherever possible and use a JavaBean called DbBean. This bean is given in Listing 18.14 and contains all the methods used by the JSP pages.

Listing 18.14 DbBean.java

package com.brainysoftware.burnaby;

import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.sql.*;

public class DbBean {
 public String dbUrl = "";
 public String dbUserName = "";
 public String dbPassword = "";

 public void setDbUrl(String url) {
  dbUrl = url;
 }
 public void setDbUserName(String userName) {
  dbUserName = userName;
 }
 public void setDbPassword(String password) {
  dbPassword = password;
 }

 public Hashtable getCategories() {
  Hashtable categories = new Hashtable();
  try {
   Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
   Statement s = connection.createStatement();
   String sql = "SELECT CategoryId, Category FROM Categories" +
    " ";
   ResultSet rs = s.executeQuery(sql);
   while (rs.next()) {
    categories.put(rs.getString(1), rs.getString(2) );
   }
   rs.close();
   s.close();
   connection.close();
  }
  catch (SQLException e) {}
  return categories;
 }

 public ArrayList getSearchResults(String keyword) {
  ArrayList products = new ArrayList();
  try {
   Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
   Statement s = connection.createStatement();
   String sql = "SELECT ProductId, Name, Description, Price FROM Products" +
    " WHERE Name LIKE '%" + keyword.trim() + "%'" +
    " OR Description LIKE '%" + keyword.trim() + "%'";
   ResultSet rs = s.executeQuery(sql);
   while (rs.next()) {
    Product product = new Product();
    product.id = rs.getInt(1);
    product.name = rs.getString(2);
    product.description = rs.getString(3);
    product.price = rs.getDouble(4);
    products.add(product);
   }
   rs.close();
   s.close();
   connection.close();
  }
  catch (SQLException e) {}
  return products;
 }

 public ArrayList getProductsInCategory(String categoryId) {
  ArrayList products = new ArrayList();
  try {
   Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
   Statement s = connection.createStatement();
   String sql = "SELECT ProductId, Name, Description, Price FROM Products" +
    " WHERE CategoryId=" + categoryId;
   ResultSet rs = s.executeQuery(sql);
   while (rs.next()) {
    Product product = new Product();
    product.id = rs.getInt(1);
    product.name = rs.getString(2);
    product.description = rs.getString(3);
    product.price = rs.getDouble(4);
    products.add(product);
   }
   rs.close();
   s.close();
   connection.close();
  }
  catch (SQLException e) {}
  return products;
 }

 public Product getProductDetails(int productId) {
  Product product = null;
  try {
   Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
   Statement s = connection.createStatement();
   String sql = "SELECT ProductId, Name, Description, Price FROM Products" +
    " WHERE ProductId=" + Integer.toString(productId);
   ResultSet rs = s.executeQuery(sql);
   if (rs.next()) {
    product = new Product();
    product.id = rs.getInt(1);
    product.name = rs.getString(2);
    product.description = rs.getString(3);
    product.price = rs.getDouble(4);
   }
   rs.close();
   s.close();
   connection.close();
  }
  catch (SQLException e) {}
  return product;
 }

 public boolean insertOrder(String contactName, String deliveryAddress,
  String ccName, String ccNumber, String ccExpiryDate, Hashtable shoppingCart) {
  boolean returnValue = false;
  long orderId = System.currentTimeMillis();
  Connection connection = null;
  try {
   connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
   connection.setAutoCommit(false);
   Statement s = connection.createStatement();
   String sql = "INSERT INTO Orders" +
    " (OrderId, ContactName, DeliveryAddress, CCName, CCNumber, CCExpiryDate)" +
    " VALUES" +
    " (" + orderId + ",'" + contactName + "','" + deliveryAddress + "'," +
    "'" + ccName + "','" + ccNumber + "','" + ccExpiryDate + "')";
   s.executeUpdate(sql);
   // now insert items into OrderDetails table
   Enumeration enum = shoppingCart.elements();
   while (enum.hasMoreElements()) {
    ShoppingItem item = (ShoppingItem) enum.nextElement();
    sql = "INSERT INTO OrderDetails (OrderId, ProductId, Quantity, Price)" +
    " VALUES (" + orderId + "," + item.productId + "," +
    item.quantity + "," + item.price + ")";
    s.executeUpdate(sql);
   }

   s.close();
   connection.commit();
   connection.close();
   returnValue = true;
  }
  catch (SQLException e) {
   try {
    connection.rollback();
    connection.close();
   }
   catch (SQLException se) {}
  }
  return returnValue;
 }
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020