You are on page 1of 34

Build a Web-based auction client

Skill Level: Intermediate Colleen Connearney (csconnea@us.ibm.com) Software Engineer IBM

23 Nov 2004 This tutorial shows you how to build a complete Web-based auction client application using the Eclipse Web Tools Platform. The auction client accesses a Cloudscape (Apache Derby) database that houses auction stock, as well as a remote auction Web service.

Section 1. Before you start


About this tutorial
The Eclipse Web Tools Platform Project is a collaborative open source software-development project dedicated to providing a generic, extensible, and standards-based tool platform upon which software providers can create specialized, differentiated offerings for both Java 2 Enterprose Edition (J2EE) and Web-centric application development. The IBM contribution to the Eclipse Web Tools Platform delivers a significant base set of tools for Web development that include data, J2EE, XML, Web services tools platform base, and a starter integrated-development environment for experienced J2EE and Web developers. This tutorial shows how to use the Web Tools Platform on Microsoft Windows to build a Web-based auction client that interacts with a local database and remote Web services provided by the auction server. Your finished site will allow you to: View your local warehouse stock

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 1 of 34

developerWorks

ibm.com/developerWorks

Examine your active auction listings Create new auction listings from warehouse stock items Query the auction site This tutorial is written for professional Java technology developers who want to improve their Web-development skills. Basic knowledge of databases, JSPs, and Web services will help you complete the tasks described. In this tutorial, you will create and populate a Cloudscape database, use example code to create JSPs, and servlets, and learn how to test your application using Apache Tomcat.

Prerequisites
This tutorial covers building an auction client, but not the accompanying Web service. To let you try out the complete application, we will point you to a running Web service we have already built for you. (Alternatively, if you would like to try your hand at building the Web service yourself, read and follow the accompanying tutorial, "Build a Web service using the Eclipse Web Tools Platform.") To complete this tutorial, you need to have the following software installed: Eclipse V3.0 The IBM contribution to the Eclipse Web Tools Platform and all of its prerequisites Apache Tomcat V4.1.30 IBM Cloudscape V10.0 You should also download the attached file, which provides SQL scripts used in this tutorial.

Section 2. Setting it up
Create the local database
Before you can begin developing the Web client, you need to create and populate

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 2 of 34

ibm.com/developerWorks

developerWorks

the local warehouse database. The contents of the database represent the warehouse stock ready to be put up for auction. To create and populate the local database: 1. 2. 3. 4. 5. If you haven't already, download and unpack the attached download, which contains the SQL script required for this section. In a command window, change the directory to <Cloudscape V10.0 install directory>\frameworks\embedded\bin. Run setEmbeddedCP.bat. Run ij.bat. At the ij> prompt, type: connect 'jdbc:derby:c:\path\warehouseDB;create=true'; (where c:\path\ is where you want to create the database). At the ij> prompt, type: run 'c:\path\warehouseDB.sql'; (where c:\path\ is the location of the warehouseDB.sql script). At the ij> prompt type: run 'c:\path\warehouseDB-populate.sql'; (where c:\path\ is the location of the warehouseDB.sql script).

6.

7.

Configure Eclipse for Tomcat V4.1


You will use Apache Tomcat to host and test your Web client. To configure Eclipse for Tomcat: 1. 2. 3. 4. 5. 6. Start Eclipse. Select Window > Preferences. Select Server > Installed Runtimes. Select Add. Select Apache > Apache Tomcat v4.1. Click Next. Browse to the Tomcat install directory.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 3 of 34

developerWorks

ibm.com/developerWorks

7. 8. 9.

Select a 1.4.2 JRE. If a 1.4.2 JRE is not configured, select Installed JREs to configure one. Click Finish. In the Preferences dialog, click OK.

10. Copy derby.jar from <Cloudscape install directory>\Cloudscape_10.0\lib\ to <Tomcat install directory>\common\lib.

Create a dynamic Web project


1. 2. 3. 4. Switch to the Java Perspective by selecting Window > Open Perspective > Java. Select File > New > Project. Select Web > Dynamic Web Project. Specify the following: Name: AuctionWebClient Web version 2.3 Target Server: Apache Tomcat 4.1 Add module to EAR project: deselect Context Root: AuctionWebClient 5. Click Finish.

Create a cascading stylesheet


The cascading stylesheet (CSS) will give all of your Web pages the same look and feel. To create a cascading stylesheet for your application: 1. 2. Right-click AuctionWebClient\WebContent. Select New > Folder.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 4 of 34

ibm.com/developerWorks

developerWorks

3. 4. 5. 6. 7.
body {

Name the folder "theme". Right-click AuctionWebClient\WebContent\theme. Select New > File. Name the file style.css. Copy and paste the following into style.css:

font-family: Georgia, "Times New Roman", Times, serif; color: navy; } table {padding:1; spacing:0; width:90%; border-collapse:collapse; } th {font-family:sans-serif; rowspan:2; text-align:left; background:000066; color:white; } td {font-family:sans-serif; border-top:ridge grey thin; border-left:none; border-right:none; padding:3; } .formtd { font-family:sans-serif; border-top:solid black thin; border-left:solid black thin; border-right:solid black thin; border-bottom:solid black thin; padding:3; } .trone{ background: #CCCCFF; } .trtwo{ background: #CCCCCC; }

If you wish, you can change the look and feel of this CSS to your own scheme.

Create the Web client home page


The Web client home page provides links to the main tasks you will implement as a part of this application.
Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 5 of 34

developerWorks

ibm.com/developerWorks

To create the Web client home page: 1. 2. 3. 4. 5. Right-click AuctionWebClient\WebContent. Select New > File. Specify index.html as the file name. Click Finish. Copy and paste the following content into index.html:

<html> <link rel="stylesheet" href="theme/style.css"> <head> <title>Seller's Web Client</title> </head> <body> <p align="center"> <FONT face="Comic Sans MS" color="navy" size="+2"> Auction Management Web Client</FONT><BR><BR><HR> </p> <p align="center"> <A href="queryWarehouse">Manage Warehouse Stock</A><BR><BR> <A href="showAuctions.jsp">Manage Auctions</A><BR><BR> <A href="queryAuctionService.html">Query Auction Site</A> </p> </body> </html>

The above HTML creates a simple page with a heading and three links.

Section 3. Creating a page to view the warehouse stock


Create the WarehouseStockItem class
You will create a Java class (WarehouseStockItem) containing the properties of a warehouse stock item. A list of these Java objects will be displayed by the Web client. 1. Create a new package: 1. Right-click AuctionWebClient\JavaSource.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 6 of 34

ibm.com/developerWorks

developerWorks

2. 3. 4. 3.

Select New > Package. Enter com.ibm.samples.Webclient as the package name. Click Finish.

Create the WarehouseStockItem Java class: 1. 2. 3. 4. Right-click AuctionWebClient\JavaSource\com\ibm\samples\Webclient. Select New > Class. Specify the class name as WarehouseStockItem. Click Finish.

5.

Implement the WarehouseStockItem class: a. Create the following private fields in the class (note that these variables correspond to the columns of the warehouse database):

private int id; private String shortName; private String itemDescription;

b.

Generate getters and setters for the above fields: 1. 2. 3. Right-click id in the source code. Select Source > Generate Getters and Setters. Click Select All, then click OK.

Create a servlet that connects to the local database


In the following steps, you will create a servlet that retrieves a list of all stock in the local warehouse database. To create the servlet class: 1. 2. Right-click AuctionWebClient\JavaSource\com\ibm\samples\Webclient. Select New > Class.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 7 of 34

developerWorks

ibm.com/developerWorks

3. 4. 5. 6.

Specify the Name: QueryWarehouseServlet. Specify the Superclass: javax.servlet.http.HttpServlet. Specify the Interface: javax.servlet.Servlet. Click Finish.

Implement the QueryWarehouseServlet


To implement the QueryWarehouseServlet: 1. Copy the following static constant definitions into QueryWarehouseServlet.java. Modify the URL to point to the location of your warehouse database.

private final static String DRIVER_CLASS \ = "org.apache.derby.jdbc.EmbeddedDriver"; private final static String URL = \ "jdbc:derby:C:\\warehouseDB";

2.

Copy the queryDB() method into QueryWarehouseServlet.java. This method connects to the warehouse database, queries the database, and returns a list of WarehouseStockItem objects created from the query result set. (See Implement QueryWarehouseServlet: Copy the queryDB() method into servlet for the code.) Copy the doGet() method into QueryWarehouseServlet.java. This method is called by the server to allow the servlet to handle a GET request. This method calls the queryDB() method, sets the results as an attribute on the HttpServletRequest object, and forwards the request to showStock.jsp. (See Implement QueryWarehouseServlet: Copy the doGet() method into servlet for the code.) Right-click anywhere in the source code and select Source > Organize Imports to add the relevant import statements.

3.

4.

(To skip over the code for Steps 2 and 3, you can go directly to the Create a JSP to display the warehouse stock section.)

Implement QueryWarehouseServlet: Copy the queryDB() method into servlet


Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 8 of 34

ibm.com/developerWorks

developerWorks

Copy the queryDB() method into QueryWarehouseServlet.java. This method connects to the warehouse database, queries the database, and returns a list of WarehouseStockItem objects created from the query result set.
private List queryDB() { List results = new Vector(); try { Class.forName(DRIVER_CLASS).newInstance(); Connection conn = null; Properties props = new Properties(); conn = DriverManager.getConnection(URL, props); Statement s = conn.createStatement(); String query = "SELECT * FROM \ warehouse.warehouse_item order by id"; ResultSet rs = s.executeQuery(query); while (rs.next()) { WarehouseStockItem ai = \ new WarehouseStockItem(); ai.setId(rs.getInt(1)); ai.setShortName(rs.getString(2)); ai.setItemDescription(rs.getString(3)); results.add(ai); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return results; }

Implement QueryWarehouseServlet: Copy the doGet() method into servlet


Copy the doGet() method into QueryWarehouseServlet.java. This method is called by the server to allow the servlet to handle a GET request. This method calls the queryDB() method, sets the results as an attribute on the HttpServletRequest object, and forwards the request to showStock.jsp.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { List results = queryDB(); RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher("/showStock.jsp"); req.setAttribute("results", results); dispatcher.forward(req, res); }

Create a JSP to display the warehouse stock


Create a JSP to display the results retrieved by QueryWarehouseServlet. Here, you will display the local stock in an HTML table.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 9 of 34

developerWorks

ibm.com/developerWorks

1.

Create the showStock.jsp file: 1. 2. 3. 4. Right-click AuctionWebClient\WebContent. Select New > File. Specify showStock.jsp as the file name. Click Finish.

3.

Copy and paste the following (Create a JSP to display the warehouse stock: Code) into showStock.jsp. This JSP retrieves the WarehouseStockItem list associated with attribute "results" and then iterates over the list and displays the ID and short name for each entry in a table.

(To skip over the code for Step 2 for now, you can go directly to the Test the Web client section.)

Create a JSP to display the warehouse stock: Code


This JSP retrieves the WarehouseStockItem list associated with attribute results and then iterates over the list and displays the ID and short name for each entry in a table.
<%@ page import="java.util.List"%> <%@ page import="java.util.Iterator"%> <%@ page import="com.ibm.samples.Webclient.WarehouseStockItem"%> <html> <link rel="stylesheet" href="theme/style.css"> <head> <title>Warehouse Stock</title> </head> <body> <h2><b>Warehouse Stock</b></h2> <TABLE> <THEAD> <TR> <TH rowspan="2">Item ID <TH rowspan="2">Title <TBODY> <% List list = (List) request.getAttribute("results"); Iterator iterator = list.iterator(); int i = 0; while (iterator.hasNext()) { i++; WarehouseStockItem item = (Warehouse\ StockItem) iterator.next(); %> <TR> <TD class=trone><%= item.getId()%> <TD class=trtwo><%= item.getShortName()%><%

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 10 of 34

ibm.com/developerWorks

developerWorks

} %> </TABLE> <p><A href="index.html">Home</A></p> </body> </html>

Test the Web client


Before testing the application, you need to add the servlet to the deployment descriptor. Note that the string "queryWarehouse" matches the first link in index.html. 1. 2. Open Web.xml in AuctionWebClient\WebContent\WEB-INF Insert the following immediately below the <display-name> element:

<servlet> <servlet-name>queryWarehouse</servlet-name> <servlet-class>com.ibm.samples.Webclient.\ QueryWarehouseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>queryWarehouse</servlet-name> <url-pattern>/queryWarehouse</url-pattern> </servlet-mapping>

3.

To test the Web client: 1. 2. 3. 4. Right-click index.html. Select Run > Run on Server. Select localhost -> Tomcat v4.1 Server @ localhost. Click Finish.

The index.html file should open in a Web browser. Currently, the only working link is the "Manage Warehouse Stock" link. Click it. The pages should be similar to the images on the following two panels.

Test the Web client: The index page


Figure 1. Index page

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 11 of 34

developerWorks

ibm.com/developerWorks

Test the Web client: The manage warehouse page


Figure 2. Manage warehouse page

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 12 of 34

ibm.com/developerWorks

developerWorks

Section 4. Making individual stock items selectable


Create links
In this section, you will create links on the showStock.jsp page so the user can select a warehouse stock item to create an auction listing form. 1. 2. Open showStock.jsp. Replace the following line: <TD class=trone><%= item.getId()%>

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 13 of 34

developerWorks

ibm.com/developerWorks

with <TD class=trone><A href="showWarehouseStockItem?itemId=<%= item.getId()%>"><%= item.getId()%></A> Now, each item ID in the table is a link to the showWarehouseStockItem. The itemId is passed as a parameter to showWarehouseStockItem.

Create a servlet that retrieves an individual warehouse item


Now, you will create the showWarehouseStockItem servlet. This servlet will handle the request, query the database for the item, and forward the request to a JSP that will display the results. 1. 2. 3. 4. 5. 6. Right-click AuctionWebClient\JavaSource\com\ibm\samples\Webclient. Select New > Class. Specify the Name: GetWarehouseStockItemServlet Specify the Superclass: javax.servlet.http.HttpServlet Specify the Interface: javax.servlet.Servlet Click Finish.

Implement the servlet


To implement the servlet: 1. Copy and paste the following static constant definitions into the body of the GetWarehouseStockItemServlet. Modify the URL to point to the location of your warehouse database.

private final static String DRIVER_CLASS \ = "org.apache.derby.jdbc.EmbeddedDriver"; private final static String URL = \ "jdbc:derby:C:\\warehouseDB";

2.

Copy the doGet() method into GetWarehouseStockItemServlet.java. This method retrieves the value of the itemId parameter, calls the queryDB() method, sets the results as an attribute on the
Trademarks Page 14 of 34

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

ibm.com/developerWorks

developerWorks

HttpServletRequest object, and forwards the request to stockItemDetails.jsp. (For the code, see Implement the servlet: Copy doGet() into servlet.) 3. Copy the queryDB() method into GetWarehouseStockItemServlet.java. This method connects to the warehouse database, queries the database, and returns the WarehouseStockItem with ID, itemId. (For the code, see the Implement the servlet: Copy queryDB() into servlet section.) Organize imports by selecting Source > Organize Imports.

4.

(To skip the code in Steps 2 and 3 for now, you can go directly to the Add GetWarehouseStockItemServlet to the deployment descriptor section.)

Implement the servlet: Copy doGet() into servlet


This method retrieves the value of the itemId parameter, calls the queryDB() method, sets the results as an attribute on the HttpServletRequest object, and forwards the request to stockItemDetails.jsp.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String itemId = req.getParameter("itemId"); WarehouseStockItem item = queryDB\ (new Integer(itemId).intValue()); RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher\ ("/stockItemDetails.jsp"); req.setAttribute("results", item); dispatcher.forward(req, res); }

Implement the servlet: Copy queryDB() into servlet


This method connects to the warehouse database, queries the database, and returns the WarehouseStockItem with ID, itemId.
private WarehouseStockItem queryDB(int itemId) { WarehouseStockItem ai = null; try { Class.forName(DRIVER_CLASS).newInstance(); Connection conn = null; Properties props = new Properties(); conn = DriverManager.getConnection(URL, props); Statement s = conn.createStatement(); String query = "SELECT * FROM \ warehouse.warehouse_item WHERE id=" + itemId; ResultSet rs = s.executeQuery(query); ai = new WarehouseStockItem();

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 15 of 34

developerWorks

ibm.com/developerWorks

rs.next(); ai.setId(rs.getInt(1)); ai.setShortName(rs.getString(2)); ai.setItemDescription(rs.getString(3)); conn.close(); } catch (Exception e) { e.printStackTrace(); } return ai; }

Add GetWarehouseStockItemServlet to the deployment descriptor


1. 2. Open the file AuctionWebClient\WebContent\WEB-INF\Web.xml Copy and paste the following immediately below the <servlet> entry for QueryWarehouseServlet:

<servlet> <servlet-name>showWarehouseStockItem</servlet-name> <servlet-class>com.ibm.samples.Webclient.GetWarehouse\ StockItemServlet</servlet-class> </servlet>

3.

Copy and paste the following immediately below the <servlet-mapping> for QueryWarehouseServlet:

<servlet-mapping> <servlet-name>showWarehouseStockItem</servlet-name> <url-pattern>/showWarehouseStockItem</url-pattern> </servlet-mapping>

Create a page to display the warehouse item


Now, you'll implement a JSP to display the results retrieved by GetWarehouseStockItemServlet. This page will display the details of a user-selected local warehouse stock item. 1. Create the stockItemDetails.jsp file: a. b. Right-click AuctionWebClient\WebContent. Select New > File.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 16 of 34

ibm.com/developerWorks

developerWorks

c. d. 3.

Specify stockItemDetails.jsp as the file name. Click Finish.

Copy and paste the following into stockItemDetails.jsp. This JSP retrieves the WarehouseStockItem associated with attribute results and then displays the item's ID, short name, and description as read-only fields in a form. The form includes an additional field (Minimum Price) and a button. These will be used to upload the selected stock item to an auction listing. You will implement this later in the exercise. (See Create a page to display the warehouse item: Code for code.) Now is a good point to stop and test the application. Click the "Manage Warehouse" link from index.html. Use the hyperlinks in the Item Id column to select and view individual stock items. Your page should look similar to the Create a page to display the warehouse item: Image section.

4.

(To skip over the code and image for now, you can go directly to the Connecting the Web client to the auction Web service section.)

Create a page to display the warehouse item: Code


This JSP retrieves the WarehouseStockItem associated with attribute results and then displays the item's ID, short name, and description as read-only fields in a form. The form includes an additional field (Minimum Price) and a button. These will be used to upload the selected stock item to an auction listing.
<%@ page import="com.ibm.samples.Webclient.WarehouseStockItem"%> <html> <link rel="stylesheet" href="theme/style.css"> <head> <title>Stock Item Detail</title> </head> <body> <%WarehouseStockItem item = (Warehouse\ StockItem)request.getAttribute("results");%> <form name="newAuctionListing" \ method="post" action="createNewAuctionListing"> <TABLE border="0"> <TBODY> <TR> <TD>Item Id:</TD> <TD><INPUT type="text" name="id" \ size="5" value=<%=item.getId() %> readonly></TD> </TR> <TR> <TD>Item:</TD> <TD><TEXTAREA rows="1" cols="60" \ name="short_name" readonly> <%=item.getShortName() %></TEXTAREA></TD> </TR> <TR>

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 17 of 34

developerWorks

ibm.com/developerWorks

<TD>Item Description:</TD> <TD><TEXTAREA rows="3" cols="40" name="description" readonly> <%=item.getItemDescription() %></TEXTAREA></TD> </TR> <TR> <TD>Minimum Price:</TD> <TD><INPUT type="text" name="minPrice" size="20"></TD> </TR> </TBODY> </TABLE> <INPUT type="submit" name="button_auction" value="Put up for auction"> </form> <p><A href="index.html">Home</A></p> </body> </html>

Create a page to display the warehouse item: Image


Figure 3. View individual warehouse item page

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 18 of 34

ibm.com/developerWorks

developerWorks

Section 5. Connecting the Web client to the auction Web service


Create a Web service client
The generated Java code provides a remote procedure call interface to the auction Web service. 1. 2. 3. 4. Select File > New > Other. Select Web Services > Web Service Client. Accept the defaults and click Next. Enter the URL to the WSDL of the running auction service: http://demo.alphaworks.ibm.com/AuctionSvr/ wsdl/com/ibm/sample/auctionsvr/ws/AuctionService.wsdl (Alternatively, if you would like to try your hand at building the Web service yourself, read and follow the accompanying tutorial, Build a Web service using the Eclipse Web Tools Platform.) Select the WSDL in the selection box. Click Next. Ensure the following values are selected and click Next: Web service runtime: Apache Axis 1.0 Server: Tomcat v4.1 Server @ localhost J2EE version: 1.3 Client type: Web Web Project: AuctionWebClient 9. Click Finish.

5. 6. 7.

Create a page to display all of your active auctions


Now you will create a page that displays all of the active auctions. If you examine the

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 19 of 34

developerWorks

ibm.com/developerWorks

AuctionService.java code generated by the Web Service Client Wizard, you will see that the getAuctions() method allows you to retrieve auctions by seller ID and auction status. 1. In index.html, you already created a link to "Manage Auctions," showAuctions.jsp. You can create that file now: 1. 2. 3. 4. 3. Right-click AuctionWebClient\WebContent. Select New > File. Specify a file name of showAuctions.jsp. Click Finish.

Copy and paste the code in the following section into showAuctions.jsp. This JSP queries the auction service for all auctions where the seller ID is "1" and the status is "OPEN." The getAuctions() method returns an array of AuctionListItems. We then iterate over this list and display various attributes of each item in a table. Examine the first column of the table -- <TD class=trone><A href="showAuctionItemDetails.jsp?itemId=<%=item.getAuctionId()%>" item.getAuctionId()%></A>. As with the warehouse stock table, each entry in the ID column is a hyperlink to details of the corresponding item. You will implement the showAuctionItemDetails JSP next.

Create a page to display all of your active auctions: Code


<%@ page import="com.ibm.www.AuctionListItem"%> <jsp:useBean id="auctionService" scope="session" \ class="com.ibm.www.AuctionServiceProxy"/> <html> <link rel="stylesheet" href="theme/style.css"> <head> <title>All Auctions</title> </head> <body> <h2><b>All Auctions</b></h2> <TABLE> <THEAD> <TR> <TH rowspan="2">ID <TH rowspan="2">Item <TH rowspan="2">Current Price <TH rowspan="2">End Time <TH rowspan="2">Status <TBODY> <% AuctionListItem[] items = auctionService.getAuctions(1,"OPEN"); for (int i = 0; i < items.length; i++)

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 20 of 34

ibm.com/developerWorks

developerWorks

{ AuctionListItem item = items[i]; %> <TR> <TD class=trone><A href="show\ AuctionItemDetails.jsp?itemId=<%= item.getAuctionId()%>"> <%= item.getAuctionId()%></A> <TD class=trtwo><%= item.getShortName()%> <TD class=trone><%= item.getCurrentPrice()%> <TD class=trtwo><%= item.getEndTime().getTime()%> <TD class=trone><%= item.getStatus()%><% }%> </TABLE> <p><A href="index.html">Home</A></p> </body> </html>

Create a page to display the details of a single auction listing


Now, you'll implement the showAuctionItemDetails JSP, which will display the details of the auction item selected in showAuctions.jsp. 1. Create the file showAuctionItemDetails.jsp: 1. 2. 3. 4. 3. Right-click AuctionWebClient\WebContent. Select File > New. Specify showAuctionItemDetails.jsp as the file name. Click Finish.

Copy and paste the following code (see the Create a page to display the details of a single auction listing: Code section) into showAuctionItemDetails.jsp. First, retrieve the value of itemId passed by showAuctions.jsp, then make a call to the auction service to retrieve an AuctionInfo object with that ID. The various properties of the AuctionInfo are displayed in a read-only form. Take a moment to test the application. From index.html, click "Manage Auctions." Use the hyperlinks in the ID column to select and view individual auction listings. (See the results in the Create a page to display the details of a single auction listing: Manage auctions page section and the Create a page to display the details of a single auction listing: Individual auction listings section.

4.

(To skip the images and code from Steps 2 and 3 for now, you can go directly to the Create a servlet to create new auction listings section.)

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 21 of 34

developerWorks

ibm.com/developerWorks

Create a page to display the details of a single auction listing: Code


<%@ page import="com.ibm.www.AuctionInfo"%> <jsp:useBean id="auctionService" scope="session" \ class="com.ibm.www.AuctionServiceProxy"/> <html> <link rel="stylesheet" href="theme/style.css"> <head> <title>Auction Item Detail</title> </head> <body> <% Integer id = new Integer(request.getParameter("itemId")); AuctionInfo info= auctionService.getAuctionInfo(id.intValue());%> <form> <TABLE border="0"> <TBODY> <TR> <TD>Id:</TD> <TD><INPUT type="text" name="text_id" \ size="5" value=<%=info.getAuctionId() \ %> readonly></TD> </TR> <TR> <TD>Item:</TD> <TD><INPUT type="text" name="text_item" size="20"\ value=<%=info.getShortName() \ %> readonly></TD> </TR> <TR> <TD>Item Description:</TD> <TD><TEXTAREA rows="3" cols="20" name="text_description"\ readonly><%=info.getItemDesc() %></ TEXTAREA></TD> </TR> <TR> <TD>Current Price:</TD> <TD><INPUT type="text" name="text_minPrice" size="20"\ value=<%=info.getCurPrice() \ %> readonly></TD> </TR> <TR> <TD>Bid Count:</TD> <TD><INPUT type="text" name=\ "text_startTime" size="20"value=<%=\ info.getBidCount() %> readonly></TD> </TR> <TR> <TD>End Time:</TD> <TD><INPUT type="text" name="text_startTime"\ size="20"value=<%=info.getEndTime().getTime()\ %> readonly></TD> </TR> <TR> <TD>Seller:</TD> <TD><INPUT type="text" name=\ "text_startTime"size="20"value=<%=info.getSeller(). getName()%> readonly></TD> </TR> <TR> <TD>Buyer:</TD> <TD><INPUT type="text" name=\ "text_startTime"size="20"value=<%\

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 22 of 34

ibm.com/developerWorks

developerWorks

=info.getBuyer()%> \ readonly></TD> </TR> </TBODY> </TABLE> <p><A href="index.html">Home</A></p> </body> </html>

Create a page to display the details of a single auction listing: Manage auctions page
Figure 4. Manage auctions page

Create a page to display the details of a single auction listing: Individual auction listings

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 23 of 34

developerWorks

ibm.com/developerWorks

Figure 5. Display details of a single auction

Create a servlet to create new auction listings


In stockItemDetails.jsp, you created a form with a button to create new auction listings. The action on that form was specified as action="createNewAuctionListing". Now you will create a servlet to create the new auction listing. To create the class CreateAuctionListingServlet: 1. 2. 3. Right-click AuctionWebClient\JavaSource\com\ibm\samples\Webclient. Select New > Class. Specify the Name: CreateAuctionListingServlet

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 24 of 34

ibm.com/developerWorks

developerWorks

4. 5. 6.

Specify the Superclass: javax.servlet.http.HttpServlet Specify the Interface: javax.servlet.Servlet Click Finish.

Implement CreateAuctionListingServlet
To implement the servlet: 1. Copy and paste the code in the next section into the body of CreateAuctionListingServlet. The doPost() method is the only implemented method: a. Retrieve the values of the parameters passed to the servlet by stockItemDetails.jsp. The AuctionService method createAuction() takes two parameters, a credentials object and an auctionInfo object. Create the credentials object using the hard-coded EMAIL and PASSWORD strings. Create the auctionInfo object from the parameters you retrieved from the request object. Create the auction. Forward the request to showAuctions.jsp so the user can view the updated auction listing table.

b. c. d. e. 2.

Organize imports by selecting Source > Organize Imports.

Implement CreateAuctionListingServlet: Code


private final static String EMAIL = "person1@ibm.com"; private final static String PASSWORD = "secreta"; private final static int SELLER_ID = 1; public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String short_name = req.getParameter("short_name"); String item_description = req.getParameter("description"); double minPrice = new Double(req.\ getParameter("minPrice")).doubleValue(); Calendar startTime = Calendar.getInstance();

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 25 of 34

developerWorks

ibm.com/developerWorks

Credentials credentials = new Credentials(); credentials.setEMail(EMAIL); credentials.setPassword(PASSWORD); AuctionInfo auctionInfo = new AuctionInfo(); auctionInfo.setSellerId(SELLER_ID); auctionInfo.setMinPrice(minPrice); auctionInfo.setShortName(short_name); auctionInfo.setItemDesc(item_description); auctionInfo.setStartTime(startTime); startTime.add(Calendar.DATE, 3); auctionInfo.setEndTime(startTime); AuctionServiceProxy service = new AuctionServiceProxy(); service.createAuction(credentials, auctionInfo); RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher("/showAuctions.jsp"); dispatcher.forward(req, res); }

Add CreateAuctionListingServlet to the deployment descriptor


Now, you'll add the servlet to the deployment descriptor. 1. 2. Open the file AuctionWebClient\WebContent\WEB-INF\Web.xml. Copy and paste the following immediately below the <servlet> entry for GetWarehouseStockItemServlet:

<servlet> <servlet-name>createNewAuctionListing</servlet-name> <servlet-class>com.ibm.samples.Webclient.\ CreateAuctionListingServlet</servlet-class> </servlet>

3.

Copy and paste the following immediately below the <servlet-mapping> entry for CreateAuctionListingServlet:

<servlet-mapping> <servlet-name>createNewAuctionListing</servlet-name> <url-pattern>/createNewAuctionListing</url-pattern> </servlet-mapping>

4.

Once again, take a moment to test the Web site. From index.html, click the "Manage Warehouse" link. Select an item to put up for auction. Enter the minimum price and click "Put up for auction." You should see the new listing in the table of active auctions (see the image in the next section).

Add CreateAuctionListingServlet to the deployment descriptor:


Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 26 of 34

ibm.com/developerWorks

developerWorks

Single warehouse item


Figure 6. View single warehouse item page

Create a page to query the auction service


Finally, you'll add the ability to query the auction service on the short name field of the auction listings. 1. Create a page to collect a search string from the user: 1. 2. 3. Right-click AuctionWebClient\WebContent. Select New > File. Specify queryAuctionService.html as the file name.
Trademarks Page 27 of 34

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

developerWorks

ibm.com/developerWorks

4. 3.

Click Finish.

Copy and paste the code in the following section into queryAuctionService.html. The page consists of a form with a text field and Submit button. When the button is pushed, the form will submit a request to showAuctionQueryResults.jsp.

Create a page to query the auction service: Code


<html> <link rel="stylesheet" href="theme/style.css"> <head> <title>Search Auction Site</title> </head> <body> <h2><b>Search Auction Site</b></h2> <p><b>What are you looking for?</b> <form name="feedback" method="post" \ action="showAuctionQueryResults.jsp"> <input type="text" name="searchTerm" size="25" /> <input type="submit" name="submitSearch"value="Go" /> </form> </p> <p><A href="index.html">Home</A></p> </body> </html>

Create a page to display the search results


Now, create a page to issue the search call to the auction service and display the results. 1. First: 1. 2. 3. 4. 3. Right-click AuctionWebClient\WebContent. Select New > File. Specify showAuctionQueryResults.jsp as the file name. Click Finish.

Copy and paste the following code (see the Create a page to display the search results: Code section) into showAuctionQueryResults.jsp. The page first retrieves the value of the searchTerm parameter passed from queryAuctions.html. Then, call the AuctionService.searchAuctions() method, passing the

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 28 of 34

ibm.com/developerWorks

developerWorks

searchTerm string. If any AuctionListItems are returned, they are displayed in a table. Otherwise, simply display a string saying zero results were found. 4. Test the application one more time. From index.html, click the "Query Auction Site" link. Enter a search term and click Go. (The Create a page to display the search results: Query page and the Create a page to display the search results: Query results page sections demonstrate this.)

Create a page to display the search results: Code


<%@ page import="com.ibm.www.AuctionListItem"%> <jsp:useBean id="auctionService" scope="session" \ class="com.ibm.www.AuctionServiceProxy"/> <html> <link rel="stylesheet" href="theme/style.css"> <body> <% String searchTerm = request.getParameter("searchTerm"); AuctionListItem[] items = auctionService.searchAuctions(searchTerm); if (items != null && items.length > 0) { %> <TABLE summary="This table shows the results of the query."> <CAPTION><EM>The results in a table are:</EM></CAPTION> <THEAD> <TR> <TH rowspan="2">ID <TH rowspan="2">Item <TH rowspan="2">Current Price <TH rowspan="2">End Time <TH rowspan="2">Status <TBODY> <% for (int i = 0; i < items.length; i++) { AuctionListItem item = items[i]; %> <TR> <TD class=trone><A href="showAuction\ ItemDetails.jsp?itemId=<%= item.getAuctionId()%>"> <%= item.getAuctionId()%></A> <TD class=trtwo><%= item.getShortName()%> <TD class=trone><%= item.getCurrentPrice()%> <TD class=trtwo><%= item.getEndTime().getTime()%> <TD class=trone><%= item.getStatus()%><% }%> </TABLE> <%} else {%> <p>The Search returned <b>0</b> results</p> <%}%> <p><A href="index.html">Home</A></p> </body> </html>

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 29 of 34

developerWorks

ibm.com/developerWorks

Create a page to display the search results: Query page


Figure 7. Query page

Create a page to display the search results: Query results page


Figure 8. Query results page

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 30 of 34

ibm.com/developerWorks

developerWorks

Section 6. Summary
In this tutorial, you've seen how to use the tools in the Eclipse Web Tools Platform to build a Web-based auction client. We used Cloudscape to build a local database and the Eclipse tools to create JSPs and servlets to build a client that interacts with both the database and remote Web services hosted by the auction server. Even though a significant amount of coding was required, the J2EE, server, and Web Services tools included in IBM's contribution to the Eclipse Web Tools Platform provided wizards, projects, and frameworks to ease the development process. To learn how to create the Web service accessed by this client, read the tutorial "Build a Web service using the Eclipse Web Tools Platform" (see Resources).

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 31 of 34

developerWorks

ibm.com/developerWorks

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 32 of 34

ibm.com/developerWorks

developerWorks

Downloads
Description
Source code Information about download methods

Name
os-wtpclientsqlscript.zip

Size
2.3KB

Download method
HTTP

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 33 of 34

developerWorks

ibm.com/developerWorks

Resources
Learn For more information about the Eclipse Web Tools Platform, visit the Eclipse Web Tools Platform. Read the Getting Started guide for IBM's contribution to the Eclipse Web Tools Platform. The Apache Tomcat Web site is the community and download site for Tomcat. IBM Cloudscape Version 10.0 lists the changes in the latest version and provides links to downloads. The companion developerWorks tutorial, "Build a Web service using the Eclipse Web Tools Platform" shows how to create the auction Web service accessed by the auction client you built here. Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products. Get products and technologies Innovate your next open source development project with IBM trial software, available for download or on DVD. Discuss Get involved in the developerWorks community by participating in developerWorks blogs.

About the author


Colleen Connearney Colleen Connearney is a software engineer with the IBM SMB Development Center in Research Triangle Park, NC. In the years she's been at IBM, she has worked as a Java and Eclipse plug-in developer with the Integrated Runtime team.

Build a Web-based auction client Copyright IBM Corporation 2004. All rights reserved.

Trademarks Page 34 of 34

You might also like