C H A P T E R  3

Creating the CDShopCart Application

This chapter describes, step by step, how to create the CDShopCart application. Before you can create the tutorial application, you must have the Sun ONE Studio 5 software installed and set up to run, and you must have the tutorial database table installed, as described in .

This chapter is organized under the following topics:

You test each component as you create it. By the end of this chapter, you will be able to run the basic application, as described in Chapter 2.



Tip - Complete source code for all JSP pages and JavaBeans components described in this chapter is found in Appendix A.




Creating a Web Module

The CDShopCart application is a web application. Web applications consist of web modules. The CDShopCart application is a very simple application, containing only one web module.

This section shows you how to implement the shopping cart features within a web module by using the Sun ONE Studio 5, Standard Edition IDE.

What Is a Sun ONE Studio 5 Web Module?

According to the Java Servlet Specification, version 2.3, "a web application exists as a structured hierarchy of directories." The root of this hierarchy is the document root, which holds all the files that are part of the web application. The hierarchy also includes a special non public subdirectory, the WEB-INF directory, for items that are related to the web application but are not to be served directly to the client. Items in the WEB-INF directory include the web deployment descriptor (the web.xml file) and servlet and utility classes used by the web application loader for loading classes.

Your application's files must eventually be part of a web module structure to package them as a WAR file (a Web ARchive format file) for delivery into a web container. The Sun ONE Studio 5 IDE's web module feature automates much of the process of creating the required directory hierarchy, as well as filling in the hierarchy with default versions of some of the objects.



Note - This tutorial does not try to provide complete information about developing web modules. For that task, see the Building Web Components book. Also, consult the Sun ONE Studio 5 online help for more details on web modules.



Creating the CDShopCart Web Module

In this section, you create the web module for the CDShopCart application. You'll use the Sun ONE Studio 5 web module feature to build this web module directory from scratch, although you could also convert an existing directory into a web module.

To create the CDShopCart web module:

1. In the Filesystems pane of the Explorer window, select the default (or any) file system and choose File right arrow New to display the New wizard.

You can use this wizard to create many different types of objects from the provided templates.

2. Open the JSPs & Servlets node and select Web Module.

New wizard's Choose Template pane showing a selected web module under the JSP & Servlet node. Activated buttons are Back, Next, Cancel, and Help. 

3. Click Next to display a page for specifying the web module directory name.

4. In the Directory field, erase the default directory filespec and type
your-directory\CDShopCart.

New wizard's Choose Target pane showing the target directory field with its ellipsis button. Activated buttons are Back, Next, Cancel, and Help. 

5. Click Finish.

The new CDShopCart web module is created in the Explorer. A dialog box appears, stating that an alternate view of the web module is installed in the Default Project window. Click OK to dismiss this message.

6. Open the nodes in the web module to reveal what has been created automatically.

Explorer window showing the CDShopCart web module and its parts.[ D ] 

Now you are ready to create the first component of the application, the ProductList JSP page.

Setting the Web Application's Context Root

In order to deploy the CDShopCart web application, the web server must know its context root. You set this as a property of the WEB-INF folder, as follows:

1. Display the WEB-INF folder's properties.

The properties window is beneath the Explorer. This is a static property window and displays the properties of whatever node is selected. Select the WEB-INF file to display its properties. Alternatively, right-click the WEB-INF folder and choose Properties. A dynamic properties window opens, which only displays the properties of the WEB-INF folder, regardless of what is selected.

2. Click in the value field of the Context Root property.

3. Type /CDShopCart and press Return (or Enter).


Using JSP Tags to Fetch and Display Database Data

In this section, you create a JSP page named ProductList that fetches and displays the CD product data. To connect to the database, retrieve the table data, and format the data for display, you'll use JSP Standard Tag Library (JSTL) tags. JSTL is from the Jakarta Project, a project of the Apache Foundation. JSTL is embedded in Sun ONE Studio 5.

For complete information on JSTL, including descriptions, examples, and a tutorial, see the Jakarta Project web site at http://jakarta.apache.org/taglibs/index.html.

What Is a JSP Tag?

The body of a JSP file can contain two types of code: fixed template data and elements.

Examples of fixed template data are XML and HTML code. You'll use HTML code in the CDShopCart application to create headings, titles, tables, and buttons.
Java classes associated with each tag implement the tag's functionality.

Standard Tags and Custom Tags

Standard tags, which are defined in the JSP specification document, are available in any JSP container. Custom tags are tags defined in an XML document called a tag library. A custom tag library is made available to the JSP page by means of a declaration in a directive element.

JSTL Tags

The JSP Standard Tag Library is a custom tag library produced by the Jakarta Project. Embedded in the Sun ONE Studio 5 IDE are JAR files that contains the JSTL tags and supporting classes and interfaces. This files are:

The two tag library descriptor (TLD) files you will use in these JAR files are sql.tld (for database actions) and core.tld (for everything else).

Using JSTL Tags

To use any JSP tags, you need to declare the tag library, and then follow the prescribed syntax of the particular tag.

For complete information on JSTL syntax conventions, see the JSTL documentation, available from the Jakarta Project web site at http://jakarta.apache.org/taglibs/index.html.

Using the taglib Directive

To use tags in a JSP page, you must first declare the tag library with a taglib directive.

The taglib directive must declare that the page uses the tag library of a given URI (Uniform Resource Identifier) and specify the tag prefix that is used in calls to actions in the library. The URI and the prefix for JSTL tags are defined with Apache JSTL conventions.

The generic syntax for the directive is:

<%@ taglib prefix="prefix" uri="http://java.sun.com/jstl/taglibname

For example, to declare the core taglib:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core

Using Tag Syntax

JSP tags are based on XML syntax and have one of two forms:

  • Start tag (the element name) plus possible attribute/attribute value pairs, an optional body, and a matching end tag
  • Empty tag with possible attributes

An example start tag you'll use in CDShopCart is the query tag, which fetches data from the data source. The query tag uses the following syntax:

<sql:query var="stored_query" dataSource="${dataSource}" >
	body
</sql:query>

An example empty tag you'll use is the sql library setDataSource tag, which creates a JDBC connection to a database. The setDataSource tag uses the following syntax:

<sql:setDataSource var="dataSource"
	url="driver_url"
	driver="driver_string"
	user="user_id" password="pwd"/>

A JSTL tag convention is to use "var" for any tag attribute that exports information about the tag. Note that "var" was chosen to emphasize the fact that this is a JSP variable, not a scripting variable, which uses the convention "id" for a variable.

Adding JSTL Tag Libraries to the Web Module

Import the JSTL tag library JAR file, standard.jar, and the JAR file of supporting classes and interfaces, jstl.jar, to the CDShopCart web module, because you will use actions that are implemented by the these files.

To import JSTL tag libraries into the web module:

1. In the Explorer, right-click the CDShopCart web module and choose Add JSP Tag Library right arrow Find in Tag Library Repository.

The JSP Tag Library Repository Browser appears.

JSP Tag Library Browser dialog box showing the standard library. Buttons are OK, Cancel, and Help. 

2. Make sure the standard file is selected and click OK.

In the Explorer, expand the lib node under the WEB-INF node.

3. Check the files are under the lib node.

The jstl.jar and standard.jar files, which contain the tags you use in this tutorial, are displayed under the lib node. Two additional jar files are also displayed. These contain APIs required for XML tags, which you will not use. All four files are also separately mounted. The Explorer looks like this:

Explorer window showing four imported tag libraries under the WEB-INF/lib folder and also mounted separately. 


Tip - Right-click the top-level Filesystems node and choose Customize. The window that opens displays all the files that are now mounted in your Sun ONE Studio 5 class path. You should be able to see the two JAR files in the list.



Creating the CD Catalog List Page

Create the mechanism for retrieving data from the database you installed in and displaying it in a table for the user. This mechanism includes:

  • A JSP page (ProductList) to hold all the code
  • Tag library declarations for the tag libraries referred to in the code
  • A setDataSource tag to connect to the database
  • A query tag to fetch to CD data
  • Iteration tags to display the CD data
  • An Add button for each CD row

The page you create looks like FIGURE 3-1.

 FIGURE 3-1 CD Catalog List Page

CD Catalog List page displayed in a web browser containing a table with five CD records plus their Add buttons.

Creating the ProductList JSP Page

Create the page that uses the tags to retrieve the CD data from the database and display the data in a table. The title of this page is CD Catalog List, and the mechanism that produces it is the ProductList JSP page.

1. In the Explorer, right-click the CDShopCart web module and choose New right arrow All Templates from the contextual menu.

The New wizard appears.

2. Expand the JSPs and Servlets node, select the JSP node under it, and click Next.

The New Object Page of the New wizard is displayed.

3. Type ProductList in the Name field and click Finish.

The ProductList JSP page is displayed in the web module.

Explorer window showing ProductList JSP page under the CDShopCart node. 

A JSP page skeleton is displayed in the Source Editor.

Source Editor showing default JSP page code.[ D ] 

Declaring the Tag Libraries

You must first declare the tag libraries as described in Using the taglib Directive. Put the directive above the body of the JSP page, right under the page title. The following procedure shows how to change the title of the page and add the directives for the two tag libraries.

1. In the body of the ProductList page, change the document title to CD Catalog List:

<head><title>CD Catalog List</title></head>

2. Underneath this line, add directives to import the core and SQL actions tag libraries, as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>

Using the setDataSource Tag to Connect to the Database

The first tag you'll use is the sql library setDataSource tag, which creates a JDBC connection to a database. First add a page heading (with an <H1> tag), then add the setDataSource tag below the <body> HTML tag to connect to the database.

1. Below the <body> tag in the ProductList page, create a page title:

<body>
<h1> CD Catalog List </h1>

2. Below the header, create the JDBC connection.

  • The following is for a PointBase driver:
  • <sql:setDataSource var="productDS"
    
    url="jdbc:pointbase:server://localhost/cdshopcart"
    
    driver="com.pointbase.jdbc.jdbcUniversalDriver"
    
    user="PBPUBLIC" password="PBPUBLIC" />
    

  • If you're using an Oracle database (using the thin driver), use this:
  • <sql:setDataSource var="productDS"
    
    url="jdbc:oracle:thin:@hostname:port#:SID"
    
    driver="oracle.jdbc.driver.OracleDriver"
    
    user="userid" password="password" />
    

The default Oracle port number is 1521.
  • If you're using a Microsoft SQLServer database with a Weblogic driver, use this:
  • <sql:setDataSource var="productDS"
    
    url="jdbc:weblogic:mssqlserver4:database@hostname:port#"
    
    driver="weblogic.jdbc.mssqlserver4.Driver"
    
    user="userid" password="password" />
    

The default port number for SQLServer is 1433.

Using the query Tag to Fetch the CD Data

Now use the sql tag, query to query the database and get a single result set containing rows of data and store it in the productQuery result set. You'll then pass this JSP variable to iterator tags to display the results. The query tag supports the standard SQL statement SELECT.

Put the query tag just after the driver tag.

To query the database for all the CD data:

single-step bulletIn the ProductList page, just after the driver tag, create a query to select all the CD data from the database (use the productDS dataSource created above):

<sql:query var="productQuery" dataSource="${productDS}" >
SELECT * FROM CD
</sql:query>

Using the Iteration Tags to Display the Data

You need to create a table and fill the table cells with the data. First, create a table with HTML tags, then use the forEach tag to iterate through the data you just fetched. Use the out tag to fetch the field data of each row.

The syntax for forEach is:

<c:forEach var="$Current_collection_item" items="${Collection}" >

The items variable holds the current collection that is the target of the iteration, and var holds the current item of that collection. If the collection is a result set, then the current item is the result set object positioned at the current row. For example, to iterate over a row from a result named myResultSet:

<c:forEach var="row" items="${myResultSet.rows}" >
<TR>
<TD><c:out value="${row.col1}"/></TD>>
<TD><c:out value="${row.col2}" /></TD>
<TD><c:out value="${row.col3}" /></TD>
</TR>
</c:forEach>

To create the table and fill the cells with data:

1. Start a table for the CD data:

<TABLE border=1>
<TR>
<TH>ID</TH>
<TH>CD Title</TH>
<TH>Artist</TH>
<TH>Country</TH>
<TH>Price</TH>
</TR>

2. Next, use the forEach and out tags to populate the table:

<c:forEach var="row" items="${productQuery.rows}" >
<TR>
<TD><c:out value="${row.ID}"/></TD>
<TD><c:out value="${row.CDTITLE}"/></TD>
<TD><c:out value="${row.ARTIST}"/></TD>
<TD><c:out value="${row.COUNTRY}"/></TD>
<TD><c:out value="${row.PRICE}"/></TD>

You will add more to this code in the next section.

Creating the Add Button for Each CD Row

Each row of the CD table holds the data for one CD. To purchase a CD, the user clicks the Add button on a CD row. Create an HTML form to define the area for user input (clicking the button) and within this area, embed information that is passed to the Shopping Cart JSP page. Add the following code immediately after the previous code:

1. Create a form for the table within a cell:

<TD>
<form method=get action="ShopCart.jsp">

2. Specify the embedded information for product ID, title, and price:

<input type=hidden name=cdId value="<c:out value="${row.ID}"/>">
<input type=hidden name=cdTitle value="<c:out value="${row.CDTITLE}"/>">
<input type=hidden name=cdPrice value="<c:out value="${row.PRICE}"/>">

3. Directly underneath the preceding code, specify the Add button:

<input type=submit name=operation value=Add>

4. End the form, the cell, and the row:

</form>
</TD>
</TR>

5. End the iteration and the table:

</c:forEach>
</TABLE>

6. Choose File right arrow Save to save your work.



Tip - To see the completed source code of this page, see ProductList.jsp Source.



Testing the ProductList JSP Page

Test your work by compiling the ProductList JSP page, deploying the web application, then executing the ProductList page. The IDE automatically launches your default browser and displays the page.

To test the ProductList page:

1. If not already started, start the PointBase Network Server by choosing Tools right arrow PointBase Network Server right arrow Start Server.

A PointBase server window is displayed. Minimize it.

2. Make sure your Sun ONE Application Server 7 admin server is running and your application server is the default web server.

See for information.

3. Make sure the Context Root property for the web module is set to /CDShopCart.

Refer to Setting the Web Application's Context Root.

4. In the Filesystems pane of the Explorer, right-click the CDShopCart web module and choose Build All from the contextual menu.

Watch the message area in the output window for status messages. If all is well, you see "Finished." If the output window displays errors. fix any problems and redo this step until you see the "Finished" message. Refer to ProductList.jsp Source for the source code.

5. Right-click the CDShopCart web module and choose Deploy.

When the application is deployed, the progress meter window closes.

6. Execute the ProductList JSP page by selecting it and clicking the Execute button in the toolbar (Execute button).

Alternatively, choose Build right arrow Execute, or right-click ProductList and choose Execute from the contextual menu.

If Sun ONE Application Server 7 is not already running, the IDE starts it (on Microsoft Windows systems, you see a command window with log messages, which you can minimize).

When the Servlet is running, the IDE opens the browser. After a few seconds, the CD Catalog List page is displayed, as in FIGURE 3-1.

Congratulations! You have successfully created a JSP page that uses JSTL tags to open a connection to a database and retrieve and display data from it. Now create the Shopping Cart page.


Creating the Shopping Cart Page and Supporting Elements

Now create the mechanism for displaying items selected for purchase from the CD Catalog List page. This mechanism includes:

  • A bean (CartLineItem) to hold the attributes of the selected CD row passed as parameters from the ProductList page
  • A beaninfo component (CartLineItemBeanInfo) to specify that id and price are properties of CartLineItem, despite having overloaded setter methods
  • Another bean (Cart) to hold the CartLineItem objects
  • The ShopCart JSP page to receive the Cart objects and display them as a row in a table
  • A Delete button for each item displayed on the Shopping Cart page
  • Cancel Order, Resume Shopping, and Place Order buttons with their implementations

When a few items have been selected, the Shopping Cart page you create looks like FIGURE 3-2.

 FIGURE 3-2 Shopping Cart Page

Shopping Cart page in a web browser showing a table of three selected CD records plus their Delete buttons. Other buttons shown for user actions.[ D ]

Creating the CartLineItem Bean

Create a line item bean whose object can hold the parameters passed to the Shopping Cart page from the CD Catalog List (ProductList) page. To do this, create three properties on the bean with their accessor methods.



Note - J2SE 1.4 requires all classes to be contained within packages, and this tutorial is compliant with J2SE 1.4. The classes subdirectory of the WEB-INF directory is not a package. Therefore, you must create a package under the classes subdirectory to hold your classes (beans). This package is called the ShopCart package in this tutorial.



1. Expand the WEB-INF node of the CDShopCart web module, right-click the Classes node, and choose New right arrow Java Package.

2. Type ShopCart for the package name and click Finish.

The new ShopCart package is displayed in the Explorer.

3. Right-click the ShopCart package and choose New right arrow All Templates.

The New wizard appears.

4. Expand the Java Beans node, select Java Bean and click Next.

5. In the Name field, type CartLineItem and click Finish.

The new CartLineItem bean is displayed in the Explorer, and its code in the Source Editor. The red badge near the bean (Bean icon with red badge) is a "need to compile" indicator. Don't worry about this; you will compile later.

6. Expand the bean and its class to reveal its contents.

7. Right-click the Bean Patterns node and choose Add right arrow Property.

8. In the New Property Pattern dialog box, define the cdtitle property.

a. Type cdtitle in the Name field.

b. Select String for the Type.

c. Enable the following options:

    • Generate field
    • Generate return statement
    • Generate set statement

The dialog box should look like this:

New Property Pattern dialog box showing example values entered. The buttons are OK, Cancel, and Help. 

9. Click OK to accept the information and close the dialog box.

10. Similarly, create the id property as follows:t

Property

Value

Name

id

Type

int

Options enabled

Generate field

Generate return statement

Generate set statement


11. And also create the price as follows:

Property

Value

Name

price

Type

double

Options enabled

Generate field

Generate return statement

Generate set statement


12. Expand the Fields node (of the CartLineItem bean class) to see the new fields you created.

Explorer window showing Fields and Bean Patterns nodes of the CartLineItem class expanded to display their contents.[ D ] 

13. Double-click one of the new fields you just created (for example, cdtitle) to see the code for it in the Source Editor.

14. Expand the Methods node to see the new get and set methods for each field.

Converting the id Property and price Property to Strings

The parameters passed from the ProductList JSP page are all passed as strings. However, because neither the id property nor price property are strings, you must convert them. An efficient way to do this is to overload the properties' setter methods and add the proper code.

To overload the setId method and setPrice methods:

1. Right-click the Methods node (of the CartLineItem bean), and choose Add Method.

2. In the Edit New Method dialog box that appears, define the setId method.

a. Type setId in the Name field.

b. Select void for Return Type.

3. In the Method Parameters box, click the Add button to display the Enter Method Parameter dialog box.

4. Define the pId parameter.

a. Select java.lang.String for the Type.

b. Type pId for the Name.

5. Click OK.

The New Method dialog box looks like this:

New Method dialog box showing example values entered. The buttons are OK and Cancel. 

6. Click OK to create the method and close the dialog box.

7. Double-click the new method in the Explorer to display its code in the Source editor.

8. Add code to this new method, as follows:

public void setId(java.lang.String pId) {
	int val = Integer.parseInt(pId);
	this.setId(val);
}



Tip - Whenever you enter code into the Source Editor by copying and pasting, you can automatically reformat it properly by putting the cursor in the Source Editor and typing Ctrl-Shift-F.



Now create the setPrice method in a similar manner.

9. Define the setPrice method as follows:

Property

Value

Name

setPrice

Return Type

void

Parameter Type

java.lang.String

Parameter Name

pPrice


10. Add the following code to this new method:

public void setPrice(java.lang.String pPrice) {
	double val = Double.parseDouble(pPrice);
	this.setPrice(val);
}

11. Select the CartLineItem bean (Bean icon with red badge), not the class (Class icon) and choose Build right arrow Compile (or press F9)

If the bean compiles without errors, the red "need to compile" badge is removed from the bean's node and you are ready to create the Cart bean. If not, check your typing and recompile.



Tip - The completed source code for this bean is found at CartLineItem Bean Source.



Creating the CartLineItemBeanInfo Component

It is a standard Java convention, built in to the Introspector class, that a bean property is a private attribute that is accessible by a pair of public accessor (get and set) methods. Because you have just overloaded the set methods for the id and price properties, the Introspector will no longer recognize these as bean properties.

However, you do want these fields to be recognized as properties, because the JSTL expression language will only make bean properties available if they follow Java conventions. For example, item that comes after the "." operator in the following code must be a property:

<TD><c:out value="${row.id}"/></TD>
<TD><c:out value="${row.cdtitle}"/></TD>

You can work around this difficulty with a BeanInfo component, with which you can specify the properties of a bean directly. Create a BeanInfo component for the CartLineItem bean, then code it to specify that id and price are properties.

To specify that id and price are properties of the CartLineItem bean:

1. Right-click the ShopCart package and choose New right arrow All Templates.

The New wizard is displayed.

2. Expand the Java Beans node, select BeanInfo w/o Icon, and click Next.

3. Name the BeanInfo CartLineItemBeanInfo and click Finish.

The new CartLineItemBeanInfo node is displayed in the Explorer.

4. Expand the BeanInfo node and its Methods node.

5. Double-click the getPdescriptor method.

The CartLineItemBeanInfo bean code is displayed in the Source Editor at the definition of the getPdescriptor method.

6. Add the following code to the body of the getPdescriptor method:

if (properties == null) {
	try {
		PropertyDescriptor[] props = {
			new PropertyDescriptor("cdtitle", CartLineItem.class),
			new PropertyDescriptor("id", CartLineItem.class),
			new PropertyDescriptor("price", CartLineItem.class)};
			properties = props;
	} catch (IntrospectionException ex) {
		return null;
	}
}



Tip - Remember to reformat code you paste or type into the Source Editor by pressing Control-Shift F.



7. Select the CartLineItemBeanInfo node and press F9 to compile the bean.

The BeanInfo bean should compile without errors.

Creating the Cart Bean

The ShopCart JSP page instantiates (or finds, if it already exists) a Cart object to hold the CD line item objects that are passed to it by the ProductList JSP page whenever a user clicks the Add button. The cart object is based on a Cart bean.

To create the Cart bean:

1. Right-click the ShopCart package and choose New right arrow Java Bean.

Notice that this item appears in the contextual menu. This shortcut is created for your convenience whenever you select an item from the New menu.

2. Name the bean Cart and click Finish.

3. Right-click the Cart bean's Bean Patterns node and choose Add right arrow Property.

4. With the New Property Pattern dialog box, create a new lineItems bean pattern, as follows:

Property

Value

Name

lineItems

Type

java.util.Vector

Selected Options

Generate field

Generate return statement

Generate set statement


The java.util.Vector type is not in the drop list, so just type it in.

You must now change the access of the lineItems field from private to public.

5. Expand the Fields node of the Cart class and select the lineItems field.

6. Display the lineItems properties and click the Modifiers value field.



Note - If the Properties window is displayed under the Explorer window, simply selecting an item displays its properties in the window. Alternatively, you can right-click lineItems and choose Properties from the contextual menu.



7. Click the ellipsis (...) button to display the Modifiers dialog box.

8. Choose Public from the Access list.

The lineItems field properties window showing the Public item being selected from the Access field's combo box list. 

9. Click OK to accept the change.

Now add code that instantiates a line item object, a method that returns the element number of a selected item, and another method that removes a line item from the cart.

10. Open the Constructors node of the Cart bean and double-click the Cart() constructor.

This action displays the Cart() constructor in the Source Editor.

11. Add the following (bold) code to the Cart bean's constructor to instantiate a new lineItems object, as follows:

public Cart() {
	propertySupport = new PropertyChangeSupport ( this );
	lineItems = new java.util.Vector();
}

12. Right-click the Cart Methods node, choose Add Method, and define the findLineItem method as follows:

Property

Value

Name

findLineItem

Return Type

int

Parameter Type

int

Parameter Name

pID


13. In the Source Editor, add the following (bold) code to the findLineItem method:

public int findLineItem(int pID) {
	System.out.println("Entering Cart.findLineItem()");
	//Return the element number of the item in the cartItems
	//as specified by the passed ID.
	int cartSize = (lineItems == null) ? 0 : lineItems.size();
	int i;
	for (i = 0; i < cartSize; i++ ) {
		if  ( pID ==
			((CartLineItem)lineItems.elementAt(i)).getId() )
		break;
	}
	if (i >= cartSize) {
		System.out.println("Couldn't find line item for ID: " +
			pID);
		return -1;
	}
	else
		return i;
}

14. Repeat Step 12, defining the removeLineItem method as follows:

Property

Value

Name

removeLineItem

Return Type

void

Parameter Type

int

Parameter Name

pID


15. Add the following code in the Source Editor to the removeLineItem method:

public void removeLineItem(int pID) {
	System.out.println("Entering cart.removeLineItem()");
	int i = findLineItem(pID);
	if (i != -1) lineItems.remove(i);
	System.out.println("Leaving cart.removeLineItem()");
}

16. Select the Cart bean (Bean icon with red badge), not the class (Class icon), and click F9 to compile the Cart bean.

The bean should compile without errors. Now create the ShopCart JSP page.



Tip - The completed source code of this bean is found at Cart Bean Source.



Creating the Shopping Cart Page

Now create the page that receives the parameters passed from the CD Catalog List page and displays some of them (id, title, and price) as a row in a table. This page also offers mechanisms for deleting an item from the table, returning to the Catalog List page, and placing the order. The title of this page is "Shopping Cart," and the mechanism that produces it is the ShopCart JSP page.

1. Create a JSP page by right-clicking the CDShopCart web module and choosing New right arrow JSP.

2. Name the JSP page ShopCart and click Finish.

The ShopCart JSP is displayed in the Explorer and in the Source Editor.

Adding Code to Add or Remove an Item From the Shopping Cart Table

Now add code that creates the cart items table. To instantiate a Cart object and a CartLineItem object, use a directive to import the Cart bean, the java.util library (the CartLineItem is a type Vector, from this library), and CartLineItem. Use the same core tags that you used in the ProductList JSP page, so also add a directive to import these tags.

Use scriptlet code to create the cart. Then add code that adds a line item created with the parameters passed from the ProductList JSP page. Add more code that deletes a line item when the user presses the Delete button. Add code to forward the action to a JSP page you will create later (the EmptyCart JSP page) if the table is empty.

As with the ProductList JSP page, use iteration tags to organize the table data. Then use a form to create the table and add a Delete button to each row.

1. Add a Page directive to import the java.util library and the ShopCart package:

<%@page contentType="text/html" %>
<%@page import="java.util.*, ShopCart.*" %>

2. Change the page title to Shopping Cart and add the directive to import the core.jar library:

<head><title>Shopping Cart</title></head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

3. Below the <body> tag, create a Shopping Cart heading for the page:

<body>
<h1> Shopping Cart </h1>

4. Below the heading, use the usebean tag to tell the JSP page to use the Cart bean:

<jsp:useBean id="myCart" scope="session" class="ShopCart.Cart" />

This code instantiates a Cart object and places it on the session.

Now specify what happens when the current operation for the session is Add. This happens when the user clicks the Add button on the ProductList page. Add code that gets the cdId, cdTitle, and cdPrice objects and adds them to the myCart object.

5. Begin the code by getting the current operation and defining what happens when a user clicks Add:

<%
String myOperation = request.getParameter("operation");
session.setAttribute("myLineItems", myCart.getLineItems());
 
if (myOperation.equals("Add")) {
CartLineItem lineItem = new CartLineItem();
lineItem.setId(request.getParameter("cdId"));
lineItem.setCdtitle(request.getParameter("cdTitle"));
lineItem.setPrice(request.getParameter("cdPrice"));
myCart.lineItems.addElement(lineItem);
}

Next, specify what happens when the current operation for the session is Delete. This happens when the user clicks the Delete button on the Shopping Cart page.

6. Use the following code to specify what happens when the user clicks Delete:

if (myOperation.equals("Delete")) {
String s = request.getParameter("cdId");
System.out.println(s);
int idVal = Integer.parseInt(s);
myCart.removeLineItem(idVal);
}

Finally, specify what happens when the Delete action deletes the last row of the Cart CD table. Use the JSP forward tag to go to the EmptyCart JSP page, which you will create soon. This last code ends the script you started in Step 5. You have to make a break for the forward tag, then resume before you finally end the scriptlet.

7. Use the following code:

//If the last item is removed from the cart...
if (((Vector)session.getAttribute("myLineItems")).size() == 0) {
//End scriptlet temporarily so that you can use the JSP 
//"forward" tag to forward to the EmptyCart page.
%>
<jsp:forward page="EmptyCart.jsp" />
//Resume the scriptlet.
<%
}
%>

Using Iteration Tags to Populate the Cart Table

Next, use the forEach and out tags to iterate through the passed data and fetch the field data of each row, much as you did in Using the Iteration Tags to Display the Data.

1. Start a table for the purchase candidate data by creating the table headings:

<TABLE border=1>
<TR>
<TH>ID</TH>
<TH>CD Title</TH>
<TH>Price</TH>
</TR>

2. Use the forEach and out tags to populate the table:

<c:forEach var="item" items="${myLineItems}">
<TR>
<TD><c:out value="${item.id}"/></TD>
<TD><c:out value="${item.cdtitle}"/></TD>
<TD><c:out value="${item.price}"/></TD>

The out tags in the preceding code retrieve the value from the named fields in the current row of the results.

3. Create a Delete button for each row, as in Adding the Buttons to the Page:

<TD>
<form method=get action="ShopCart.jsp">
<input type=hidden name=cdId value="<c:out value="${item.id}"/>">
<input type=hidden name=cdTitle value="<c:out value="${item.cdtitle}"/>">
<input type=hidden name=cdPrice value="<c:out value="${item.price}"/>">
<input type=submit name=operation value="Delete">
</form>
</TD>
</TR>
</c:forEach>
</TABLE>

Adding the Buttons to the Page

Finally, add the Resume Shopping, Place Order, and Cancel Order buttons to the page bottom.

single-step bulletAdd the following code to the ShopCart JSP page:

<p>
<!--Create the three buttons.-->
<form method=get action="ProductList.jsp">
<input type=submit value="Resume Shopping">
</form>
<form method=get action="PlaceOrder.jsp">
<input type=submit value="Place Order">
</form>
<form method=get action="CancelOrder.jsp">
<input type=submit value="Cancel Order">
</form>
</p>
<!End the page.>
</body>
</html>



Tip - To see the completed source code of this page, see ShopCart.jsp Source.



Testing the Shopping Cart Page

You do not test the ShopCart page directly. You test the ProductList page and navigate (by means of the Add button) to the Shopping Cart page. First, you have to redeploy the CDShopCart web application, because it contains components that were not in the previously deployed version.



Note - Make sure Sun ONE Application Server 7 is the default web server of the IDE. See for information.



1. If not already started, start the PointBase Network Server by choosing Tools right arrow PointBase Network Server right arrow Start Server.

2. Right-click the CDShopCart web module and choose Build All.

3. Right-click the CDShopCart web module again and choose Deploy.

The IDE redeploys the application. A progress window is displayed, showing the progress of the deployment process, then goes away when the process is completed.

4. Right-click the ProductList JSP page and choose Execute.

The IDE launches the default browser and displays the CD Catalog List page.

5. Click one of the Add buttons to navigate to the Shopping Cart page.

The Shopping Cart page looks similar to this example:

Shopping Cart page in a web browser showing a table with a single CD record and its Delete button. Other buttons are for user actions.[ D ] 

6. Use the Resume Shopping button to return to the CD Catalog List page.

You have almost finished the CDShopCart application. You only have to create the EmptyCart and PlaceOrder pages, and you're done.


Creating the Three Message Pages

Now create a JSP page that is displayed when a user empties the cart and two other pages that are displayed when the user clicks the Place Order and Cancel Order buttons.

Creating the Empty Cart Page

When an iterator tag finds an empty vector, it throws an exception rather than creating an empty table. You have dealt with this by testing for this case (Step 7 in Adding Code to Add or Remove an Item From the Shopping Cart Table) and then you handled the exception by displaying the Empty Cart page. This page contains a Resume Shopping button that enables the user to return to the product list page.

 FIGURE 3-3 Empty Cart Page

Empty Cart page in a web browser showing a message saying the shopping cart is empty and a Resume Shopping button.

To create the Empty Cart page:

1. Right-click the CDShopCart web module and choose New right arrow JSP.

2. Type the name EmptyCart and click Finish.

The EmptyCart JSP page appears in the Explorer and its source in the Source Editor.

3. Change the page title to Empty Cart and add code as follows:

<%@page contentType="text/html"%>
<html>
<head><title>Empty Cart</title></head>
<body>
<H1> Empty Cart </H1>
<!--Display a message-->
Your shopping cart is empty.
<P>
<!--Add a Resume Shopping button.-->
<form method=get action="ProductList.jsp"> 
<input type=submit value="Resume Shopping">
</FORM>
</P>
</body>
</html>

4. Save the EmptyCart page by choosing File right arrow Save.

Creating the Place Order Page

The Place Order and Cancel Order pages are very simple pages, and represent only one of many ways you can implement these actions. Because programming these pages demonstrates little more of the Sun ONE Studio 5 features than you have already seen, the tutorial uses the simplest possible implementation.

The Place Order page is displayed when the user clicks the Place Order button on the Shopping Cart page. Displaying this page ends the session.

 FIGURE 3-4 Place Order Page

Place Order page in a web browser showing a message saying the order has been placed, thank you for shopping, and Resume Shopping button.

To create the Place Order page:

1. Right-click the CDShopCart web module and choose New right arrow JSP.

2. Type the name PlaceOrder and click Finish.

3. Change the page title to Place Order and add code as follows:

<%@page contentType="text/html"%>
<html>
<head><title>Place Order</title></head>
<body>
<H1> Place Order </H1>
<!--Invalidate the session-->
<%
session.invalidate();
%>
Your order has been placed. Thank you for shopping.
<P>
<FORM method=get action="ProductList.jsp">
<INPUT type=submit value="Resume Shopping">
</FORM>
</P>
</body>
</html>

4. Save the PlaceOrder page by choosing File right arrow Save.

Creating the Cancel Order Page

The Cancel Order page is displayed when the user clicks the Cancel Order button on the Shopping Cart page. Displaying this page ends the session. The page looks like FIGURE 3-5.

 FIGURE 3-5 Cancel Order Page

Cancel Order page in a web browser showing a message saying the order has been canceled; thank you for shopping, and a Resume Shopping button.

To create the Cancel Order page:

1. Right-click the CDShopCart web module and choose New right arrow JSP & Servlet right arrow JSP.

2. Type the name CancelOrder and click Finish.

3. Change the page title to Cancel Order and add code similar to the PlaceOrder page, as follows:

<%@page contentType="text/html"%>
<html>
<head><title>Cancel Order</title></head>
<body>
<H1> Cancel Order </H1>
<%
session.invalidate();	
%>
Your order has been cancelled. Thank you for shopping.
<P>
<FORM method=get action="ProductList.jsp">
<INPUT type=submit value="Resume Shopping">
</FORM>
</P>
</body>
</html>

4. Save the CancelOrder page by choosing File right arrow Save.

Testing the Three Message Pages

As with the Shopping Cart page, test the message pages by running the ProductList JSP page. Then add CD items to the Shopping Cart and perform an appropriate action to display each message page. First, you have to redeploy the CDShopCart web application, because it contains components that were not in the previously deployed version.



Note - Make sure Sun ONE Application Server 7 is the default web server of the IDE. See for information.



1. If not already started, start the PointBase Network Server by choosing Tools right arrow PointBase Network Server right arrow Start Server.

2. Right-click the CDShopCart web module and choose Build All.

3. Right-click the CDShopCart web module again and choose Deploy.

The IDE redeploys the application. A progress window is displayed, showing the progress of the deployment process, then goes away when the process is completed.

4. Right-click the ProductList JSP page and choose Execute.

The IDE launches the default browser and displays the CD Catalog List page.

5. Click one of the Add buttons to navigate to the Shopping Cart page.

6. To test the Empty Cart page, click the Delete button on the item you just put into the cart.

The Empty Cart page appears.

7. Click the Resume Shopping button to return to the CD Catalog List page.

8. Add one or more CDs to the cart.

9. Test the Cancel Order page by clicking the Cancel Order button.

10. When the page appears, click the Resume Shopping button to return to the CD Catalog List page.

11. Add another CD to the cart.

12. When the Shopping Cart page appears, make sure that the CD you added is the only one in the cart.

There should be only one CD in the cart because the Cancel Order action (Step 9) ended the previous session.

13. Add more CDs to the cart, and then test the Place Order button.

14. When the Place Order page appears, click the Resume Shopping button to return to the Catalog page.

15. Add another CD to the cart.

The Place Order page ended the session. Therefore only one CD should be in the cart.

16. To stop the application, direct the browser to a different URL.

You have completed the CDShopCart application.