Home > Articles

  • Print
  • + Share This
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;
 }
}
  • + Share This
  • 🔖 Save To Your Account