
Developing E-Commerce Applications using BEA Weblogic Server 4.0.0 and Java Servlets
This paper provides an overview of building a Web-based application using BEA Weblogic Server 4.0.0 and Java Servlets. The paper describes setting up the Weblogic Server environment for servlet development and using JDBC to communicate with a Resource Manager such as Oracle RDBMS.
This paper will serve as an introduction to other papers that will follow and will focus on the different implementations that Weblogic has to offer, including EJB and integrating with BEA Jolt and Tuxedo.
In the following sections we will learn how to build a complete web-based application using Weblogic Server and HTTP Servlets.
You may expect to learn the following by the end of this paper:
- Setting up Weblogic Server 4.0.0 for servlet development.
- Session Tracking to avoid redundant connections to the Resource Manager.
- Writing Servlets that use JDBC to communicate with the Resource Manager.
- Using HTMLKona for HTML generation.
At the completion of the document you will be able to get a good comprehension of developing web-based applications using servlets and Weblogic Server.
You will need the following set of tools to work on this example:
We will be constructing an On-line Sporting Goods Shopping Site. The site will provide a way to search for products sold by a vendor. Products found that match the criteria are presented to the customer. The customer may then enter the quantity for each product and proceed to complete his/her shopping. The order is completed once the customer enters a valid Identification and password. This application assumes that the user has an account with the vendor.
This paper assumes that you have:
- Experience writing java code
- Familiar with packages, CLASSPATH variables, and java compiler options
- Dabbled with Weblogic Server
Return to Top of Page
Servlets are written in Java and are hence platform independent. Most popular Web servers support them. Servlets are deployed on the server making them extremely efficient. They can function entirely within the confines of a web server. This feature does not require the browsers invoking them to support Java.
One of the major advantages of using Servlets is that they act just like Server Extension APIs where for each request a new process is not started but are handled by separate threads. CGI and Fast CGI scripts on the other hand mandate a process for each request, which could result in a loss in efficiency of the web server.

Application Architecture
Return to Top of Page
Using the ServletServlet service servlet provided by WebLogic, you can dynamically load or change your servlets during the prototyping phase of your application development.
I say this is neat because typically you are supposed to register your servlets in the weblogic.properties file. So every time you make a subtle change to your servlet you would have to shutdown the server and then restart it again and this process could take a good 3-4 minutes depending on your machine’s configuration.
In order to register your ServletServlet servlet open your weblogic.properties file (this is saved in the \weblogic root directory and the file name is weblogic and the extension is properties) in an editor that can handle large files. Notepad will not do the trick for you.
Locate the following entry:
weblogic.httpd.register.servlets=weblogic.servlet.ServletServlet
and remove the comment symbol "#"
Now locate the following entries:
weblogic.httpd.servlet.classpath=
weblogic.httpd.servlet.reloadCheckSecs=
and remove the comment symbol "#"
The 2 entries above MAY look like the following:
weblogic.httpd.servlet.classpath=c:/weblogic/reload_classes
weblogic.httpd.servlet.reloadCheckSecs=5
The first entry defines the servlet classpath for the compiled servlets that you will be developing. I use the word may because the servlet classpath may be any directory where you intend to save your compiled (.class) servlets. Ensure that you use "/" slashes and not "\" in the case of Windows users. Forward slashes must always be used immaterial of the platform.
The second entry informs the server to load the latest servlet class after the specified number of seconds.
If you intend to use any images in your html generated files then they must be stored in the following directory: \weblogic\myserver\public_html\
This is the default directory that the application server will use to locate all .html, .shtml, images files.
At this point your Application Server is ready to be started. To start the Weblogic Server go to Start -> Programs -> Weblogic 4.0.0 and select the Weblogic Server option.
Then, go to the same location under your Start menu and select the Weblogic Console also.
When the Weblogic console starts up type in the password (may be found in the weblogic.properties file under the entry weblogic.password.system=javaapps) and select 'Connect'. Your server will be ready once the console successfully connects to the server.
Return to Top of Page
The introductory home page of the On Line shopping application is an HTML file that can be generated using any Page Authoring Tool.
Fig 1 shows us what the home page for our On-line Shopping E-Commerce Application looks like.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">
<META NAME="GENERATOR" Content="Visual Page 2.0 for Windows">
<TITLE>Sports Shopping Spree</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFBF0">
<P>
<IMG SRC="Images/aisilogo(1).gif" WIDTH="175" HEIGHT="91" ALIGN="BOTTOM"
BORDER="0">
</P>
<P>
<FONT SIZE="4" COLOR="#CC0000" FACE="Arial">
Welcome to the On Line Shopping Network:</FONT></P>
<P>
<HR ALIGN="CENTER" SIZE="4" NOSHADE>
</P>
<FORM ACTION="http://localhost:7001/servlets/examples/servlets/ProductList"
METHOD="GET">
<P>
<FONT COLOR="#000099" FACE="Century Gothic" Size ="13pt">
<B>Search for :</FONT></B>
<FONT SIZE="4" COLOR="#CC0000"FACE="Arial">
<INPUT TYPE="TEXT" NAME="Search" SIZE="25"></FONT></P>
<P>
<INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Search">
<INPUT TYPE="RESET" NAME="Reset" VALUE="Reset"></P>
</FORM>
<P> </P>
<P> </P>
<P> </P>
<P> </P>
<HR ALIGN="CENTER">
</BODY>
</HTML>
|
The bold text in the code above is the call to the servlet ProductList that is saved in the c:\weblogic\reload_classes\examples\servlets directory. The name of the input element is "Search" that is sent in the HTTP request to the ProductList servlet.
The ProductList servlet uses the search criteria entered by the user to perform a search on the database.
Once a user enters the search criteria and clicks the Submit button the ProductList servlet is invoked. This occurs because the ACTION attribute is assigned an URL of the Servlet that needs to be invoked. The GET method is used because all the data entered in the input elements will be appended to the request URL as a query string. Only one ACTION property may be set for a form. All input elements that have the INPUT TYPE property as "SUBMIT", will cause the URL in the ACTION property to be triggered.
Return to Top of Page
This is the first servlet that is invoked by our application. The Servlet uses the HTTP request parameter to retrive the search criteria entered by the user in the search page. Using this search criteria it first instantiates the TrackSession object (explained in the next section) to get a connection to the Database.
Using the weblogic.html package constructs the HTML page to be sent back to the browser with the results obtained from the database. Once the user receives the search results the user may determine the quantity required for each product and may select the ‘Proceed to Checkout’ button which will in turn invoke the OrderForm servlet.
The HTML generated page sent to the browser looks like the following:
 Figure 2
The following is a code listing of the ProductList Servlet:
// Author: Sanjay Bansal
// Company: Aurora Information Systems
// Date: May 03, 1999
// Description: This class serves as the ProductList servlet and is
// used to produce an HTML page that displays a list of products that
// match the search criteria sent in the HttpServletRequest object.
// the HTML page has a button that on being selected invokes the
// OrderForm servlet.
package examples.servlets;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import weblogic.html.*;
public class ProductList extends HttpServlet {
public void init (ServletConfig config) throws ServletException
{
super.init(config);
try {
Class.forName ("oracle.pol.poljdbc.POLJDBCDriver");
}
catch (ClassNotFoundException e)
{
}
}
public void service (HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException
{
ServletPage page = new ServletPage("Home Shoping");
ServletPage page.setBackgroundColor("#FFFBF0");
Vector prodVector = new Vector();
String prodString = "";
// Instantiate the TrackSession object to get a connection
// to the database
TrackSession tSession = new TrackSession (req);
try
{
String searchString = req.getParameterValues("Search")[0];
if (searchString == null)
{
searchString = "";
}
else
{
searchString = "where name like '" + searchString + "%'";
}
// Call the getResult method from the TrackSession object
// to retrieve a list of products.
ResultSet rs = tSession.getResult
("SELECT * FROM PRODUCT_LIST" + searchString);
TableElement tab =new TableElement();
String titleString = "Sports On-Line Shopping Network";
//Start constructing the HTML page.
page.getHead().addElement(new ImageElement
("/Images/aisilogo(1).gif"));
page.getHead().addElement(" ");
page.getHead().addElement(new StringElement(titleString)
.asFontElement("+2")
.asBoldElement());
page.getHead().addElement(new HorizontalRuleElement()
.asFontElement("+2"));
page.getBody().addElement(new StringElement ("Product Information")
.asFontElement("+2")
.asBoldElement());
// Create a loop to process every record returned by
//the resultset.
while (rs.next())
{
// Here name is the column name in the table stored in the database
// Here although not necessary the name of the product is being
// stored in a vector in the event of further processing with
// the names.
// You could directly access the data from the resultset as being
// done for the Cost and the Product id.
prodString = rs.getString("name");
prodVector.addElement(prodString);
tab.addElement(new TableRowElement()
.addElement(Long.toString(rs.getLong("id")))
.addElement(prodString.toString())
.addElement("$" + Float.toString(rs.getFloat("cost")))
.addElement(new InputElement(prodString.toString())
.setSize(5)
.setMaxlen(3)
.setValue(""))
.addElement (new ImageElement("/Images/special.gif")
.setHeight(18)
.setWidth(72)));
}
// Add an action to the generated HTML page and map the 'POST'
// method to it. This will cause the OrderForm Servlet to be
// invoked when the 'Proceed to Checkout' button is clicked
FormElement form = new FormElement("OrderForm", "POST");
form.addElement(tab);
form.addElement(MarkupElement.BeginParagraph);
form.addElement(" ");
form.addElement(MarkupElement.EndParagraph);
// Add the 'Proceed to Checkout' button to the form.
form.addElement (new InputElement ("SUBMIT",FieldType.submit)
.setValue("Proceed to Checkout"));
page.getBody().addElement (form);
}
//raise an exception if anything goes wrong.
catch (SQLException e)
{
page.getBody().addElement("Problem with SQL");
}
catch (Exception e1)
{
page.getBody().addElement(new StringElement("Sorry: " + e1));
}
res.setContentType("text/html");
// Send the HTML page to the browser
page.output(res.getOutputStream());
}
}
|
Pointer 1:
ServletPage page = new ServletPage("Home Shoping");
Here we are instantiating an object page of class ServletPage. This will ultimately be the HTML generated page that will be sent to the browser. Return to Code
Pointer 2:
TrackSession tSession = new TrackSession (req);
See section Using the TrackSession Class in the next section. Return to Code
Pointer 3:
Here the search string that user entered is being retrieved from the HTTP req argument that is later used to retrieve information from the database. Return to Code
Pointer 4:
FormElement form = new FormElement("OrderForm", "POST");
Here the servlet informs the browser that when the user selects the "Proceed to Checkout" button the OrderForm servlet must be invoked. Return to Code
Return to Top of Page
The TrackSession Class is used to establish the communication between the servlets and the database. It makes a connection to the database if there is not already one for the session.
This ensures that every time a request is made to the database a new connection is not created as this could slow down the system and because database connections are the most expensive in terms of resources for a JDBC application.
The source code is listed below:
// Author: Sanjay Bansal
// Company: Aurora Information Systems
// Date: May 03, 1999
// Description: This class serves as a resource pool manage the number of
// connections to the database.
package examples.servlets;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TrackSession {
private Connection conn = null;
public HttpSession sessionLocal;
// ConnectionHolder is an implementation of
// the HttpSessionBindingListener class
private ConnectionHolder holder = null;
public TrackSession (HttpServletRequest req)
{
try
{
// Get the current session object.
// If one is not created then create one
sessionLocal = req.getSession(true);
// Check if there is already a connection
// established with the database
holder = (ConnectionHolder)
sessionLocal.getValue ("servletapp.connection");
// If not then initiate one.
if (holder == null)
{
try
{
holder = new ConnectionHolder
(DriverManager.getConnection
("jdbc:polite:POLITE", "system", "passwd"));
sessionLocal.putValue("servletapp.connection", holder);
}
catch (Exception e)
{
}
}
// Get the connection. This will be either the one
// initiated above or one that was found already
conn = holder.getConnection();
}
catch (Exception e)
{
}
}
// The following method was created to provide a uniform reusable way
// to get a Resultset from the database. The SQL select statment is
// sent as a parameter and the statement is executed and the ResultSet
// is sent back to the calling object.
public ResultSet getResult(String stmnt)
{
ResultSet rs = null;
try
{
Statement stmt = conn.createStatement();
stmt.executeQuery(stmnt);
rs = stmt.getResultSet();
}
// If an error occurs then drop the connection
// object to the database
catch (Exception e)
{
sessionLocal.removeValue("servletapp.connection");
}
return rs;
}
}
|
Pointer1:
We are looking to see if a connection to the database is already stored in the session variable. If not then we are requesting for a connection and storing it in the session variable "servletapp.connection".
Return to Code
Pointer2:
Here we are instantiating an object of class ConnectionHolder that is explained in detail in the next section.
Return to Code
Pointer3:
This method is used throughout the application to retrieve data from the database for the Select string sent to it as an argument. The data retrieved from the database is sent back as a ResultSet.
Return to Code
Return to Top of Page
This class implements the HttpSessionBindingListner abstract class and is used to store the connection made to the database. The ConnectionHolder class is also responsible for the life of the connection and closes the connection to the database when the session expires (i.e when the browser is closed).
The source code is listed below:
// Author: Sanjay Bansal
// Company: Aurora Information Systems
// Date: May 03, 1999
// Description: This class implements the
// HttpSessionBindingListner abstract class
package examples.servlets;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
class ConnectionHolder implements HttpSessionBindingListener
{
private Connection con = null;
public ConnectionHolder (Connection con)
{
this.con = con;
try
{
// Set AutoCommit to false for transaction support
con.setAutoCommit(false);
}
catch (SQLException e)
{
}
}
// return the current conneciton.
public Connection getConnection ()
{
return con;
}
//Since this is an implementation of an abstract class every
//method needs to be implemented.
public void valueBound(HttpSessionBindingEvent event)
{
}
// When the connection is removed close
// the connection to the database.
public void valueUnbound(HttpSessionBindingEvent event)
{
try
{
if (con != null)
{
con.rollback();
con.close();
}
}
catch (SQLException e)
{
}
}
}
|
Return to Top of Page
This is the last of the servlets that we will be developing for this application. This servlet performs quite a few tasks. It is invoked once the user has entered the quantity of each product that he/she wants to purchase and wishes to checkout from our On-line store.
The servlet first uses the HTTPServlet request parameter to determine the product that the customer wants to purchase.
It then generates an HTML table listing all the products that the customer has requested to purchase and an interface for the customer to enter its login identification and password (as seen in the figure below) to confirm the order.
Once the user clicks on the Confirm Order button the OrderForm servlet is invoked again. The servlet now confirms the customer login identification and password from the database. If the verification is successful it sends the order to the database and on successful insertion of the order in the database posts a confirmation to the customer (as seen in the figure below).
Code Listing for OrderServlet:
// Author: Sanjay Bansal
// Company: Aurora Information Systems
// Date: May 03, 1999
// Description: This class serves as the OrderForm servlet and is used to
// produce an HTML page that displays the order being placed by the
// customer and provides an interface to confirm the same.
package examples.servlets;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import weblogic.html.*;
public class OrderForm extends HttpServlet {
public void init (ServletConfig config) throws ServletException
{
super.init(config);
try {
Class.forName ("oracle.pol.poljdbc.POLJDBCDriver");
}
catch (ClassNotFoundException e)
{
}
}
public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
ServletPage page = new ServletPage("Aurora Shopping Order Form");
res.setContentType("text/html");
try
{
String titleString = "Sports On-Line Shopping
Network Order Form Confirmation";
//Set up the Header for the Order Confirmation HTML page.
page.getHead().addElement(new ImageElement("/Images/aisilogo(1).gif"));
page.getHead().addElement(" ");
page.getHead().addElement(new StringElement(titleString)
.asFontElement("+2")
.asBoldElement());
page.getHead().addElement(new HorizontalRuleElement()
.asFontElement("+2"));
// If the method is not 'GET' perform the following. When the servlet
// is invoked from the HTML file produced from the ProducList Servlet
// this part of the code will be executed.
if ((req.getMethod().equals("GET")) == false)
{
Enumeration orderList = req.getParameterNames();
String nameOfProd = new String();
String qtyOfProd = new String();
int qtyInt;
TableElement tab = new TableElement();
// The list of products that the customer wants to buy will
// be retrieved from the HTTPServletRequest object.
// Only the products where a quantity is mentioned will
// be embed into the HTML page being generated.
while (orderList.hasMoreElements())
{
nameOfProd = (String) orderList.nextElement();
qtyOfProd = req.getParameterValues(nameOfProd)[0];
try
{
qtyInt = Integer.parseInt(qtyOfProd);
tab.addElement(new TableRowElement()
.addElement(nameOfProd)
.addElement(new InputElement(nameOfProd)
.setSize(5)
.setMaxlen(3)
.setValue(qtyOfProd)));
}
catch (NumberFormatException NumberExE)
{
}
} // end while
// Add a method "GET" to the form in the HTML page generated
// that will invoke this servlet again.
// This method is triggered when the customer enters its
// login id and password and wants to commit to his purchase order.
FormElement form = new FormElement("OrderForm", "GET");
form.addElement(tab);
form.addElement(MarkupElement.BeginParagraph);
form.addElement(" ");
form.addElement(MarkupElement.EndParagraph);
form.addElement("Login:");
// Add HTML Elements to the HTML page for confirmation of the
// order. This includes an interface to enter a login id and
// password.
form.addElement(new InputElement ("login")
.setSize(25)
.setMaxlen(25)
.setValue(""));
form.addElement(MarkupElement.BeginParagraph);
form.addElement(MarkupElement.EndParagraph);
form.addElement("Password:");
form.addElement(new InputElement ("password")
.setSize(40)
.setMaxlen(40)
.setValue("")
.setType(new FieldType("PASSWORD")));
form.addElement(MarkupElement.BeginParagraph);
form.addElement(MarkupElement.EndParagraph);
// add a button to the page
form.addElement (new InputElement ("SUBMIT",FieldType.submit)
.setValue("Confirm Order"));
page.getBody().addElement (form);
// we are now ready to come out of the servlet to show
// the customer the products requested for order and to
// get a confirmation.
} // end of if
// This part of the code is invoked only if the OrderServlet calls
// itself to perform the confirmation of the order.
else
{
Enumeration paramList = req.getParameterNames();
String logid = "login";
String password = "password";
String currentVal = "";
TrackSession tSession = new TrackSession (req);
while (paramList.hasMoreElements())
{
currentVal = (String) paramList.nextElement();
if (password.equals(currentVal))
password = req.getParameterValues(currentVal)[0];
else if (logid.equals(currentVal))
logid = req.getParameterValues(currentVal)[0];
}//end while
// Confirm to see if the user id and password is correct.
// Call the tSession object to get the verification
// from the database.
ResultSet rs = tSession.getResult
("select id from user_accounts where login = '" + logid +
"' and password = '" + password + "'");
rs.next();
// If no record was found then the verification failed.
if (rs.getInt(1) <= 0)
page.getBody().addElement
("Password not correct for entered Login Id.");
// If verification was successful then insert all the
// orders into the database.
else
{
int custId = rs.getInt(1);
try
{
// Get the connection to the database
Connection con = tSession.getConnection();
//Prepare a SQL statement to perform the insert.
PreparedStatement SQLStmt = con.prepareStatement(
"insert into cust_order values (?,?,?,?,?,?)");
//Get the order information from the HTTPServletRequest Object.
paramList = req.getParameterNames();
while (paramList.hasMoreElements())
{
String nameOfProd = (String) paramList.nextElement();
String qtyOfProd = req.getParameterValues(nameOfProd)[0];
try
{
int qtyInt = Integer.parseInt(qtyOfProd);
//Get the cost of the product requested
ResultSet orderSpec = tSession.getResult
("SELECT ID,COST FROM PRODUCT_LIST WHERE NAME
= '" + nameOfProd + "'");
orderSpec.next();
// Map data to all the columns where data will be inserted
// to table in the database.
if (orderSpec.getLong("ID") >= 0)
{
try
{
SQLStmt.setString(1,req.getRequestedSessionId());
SQLStmt.setLong(2,orderSpec.getLong("ID"));
SQLStmt.setInt(3,qtyInt);
SQLStmt.setLong(4,custId);
SQLStmt.setTimestamp(5, new Timestamp
(System.currentTimeMillis()));
SQLStmt.setFloat(6, (qtyInt * orderSpec.getFloat("COST")));
// Make the call to insert the record.
SQLStmt.executeUpdate();
} // end of try
catch (SQLException SQLE)
{
page.getBody().addElement("SQL INSERT ERROR");
}
} //if
}
catch (NumberFormatException NumberE)
{
}
} //end of tryin while
// Once the order is inserted convey confirmation
// to the customer.
page.getBody().addElement(MarkupElement.BeginParagraph);
page.getBody().addElement("Thank You for shopping
at Sports Shopping Spree." );
page.getBody().addElement(MarkupElement.EndParagraph);
page.getBody().addElement(MarkupElement.BeginParagraph);
page.getBody().addElement("Your order has been proccessed and
will reach you in 3 business days.");
page.getBody().addElement(MarkupElement.EndParagraph);
//Commit the transaction
con.commit();
}
catch (Exception e)
{
page.getBody().addElement("Failed to Place Order.");
}
} //end else of Passwd
}// end else
}// end of try
catch (Exception Finale)
{
page.getBody().addElement("Error in Processing. Please try again");
}
page.output(res.getOutputStream());
} // end of service
} // end of servlet
|
Pointer 1:
When the OrderForm servlet is called from the ProductList generated HTML file this part of the code is executed as the method in the HTTPServlet request is "POST".
Return to Code
Pointer 2:
Here the method "GET" is being added to the form in the HTML page generated. This will invoke this servlet again. This method is triggered when the customer enters its login id and password and wants to commit to his purchase order.
Return to Code
Pointer 3:
After the customer enters the valid logid and password the OrderForm servlet is invoked again and the servlet starts executing from this point.
Return to Code
Pointer 4:
Here we are performing a verification of the customer account.
Return to Code
Pointer 5:
Here we are performing a request to the database to insert the order for the customer.
Return to Code
Pointer 6:
Here we are committing the transaction with the database.
Return to Code
Return to Top of Page
BEA Weblogic Server provides a good development environment to develop web based applications. The servlet implementation of developing E-Commernce applications gives us a good understanding of how to set up the application server for development.
Weblogic webserver provides capability to a varied choice of implementations to develop robust distributed object oriented Java based E-Commerce applications using RMI, EJB, servlets etc.
In the next paper we will tackle the EJB implementation of the very same application using Weblogic Application Server.
Return to Top of Page
"Weblogic Developers Guide - Using Weblogic HTTP Servlets", BEA Systems.
Jason Hunter, William Crawford, "Java Servlet Programming", O’Reilly, Sebastopol, CA, 1998
~end of Aurora Information Systems White Paper Series #7
"Developing E-Commerce Applications using BEA Weblogic Server 4.0.0 and Java Servlets"~
Return to Top of Page
Do you find this information interesting?
Consider employment with Aurora!
|
|
Do you need help implementing your Middleware app? Aurora can make your life easier.
|
|