Getting Started with Java Servlets using Apache JServ - Examples (
Page 3 of 5 )
As stated previously, one of the big benefits of using Java on the server is
the ability to use any of large number of API's available for Java. One of the
more common tasks in creating a web-enabled application is to make the html
pages driven from a database. The following shows a simple example of a servlet
accessing a database via JDBC. The database which my sample servlet will be
connecting to is MySQL, a robust open-source
database which has gained popularity in web applications because of it's
reliability and blazing speed. For this example, you'll also need a JDBC driver
for MySQL. One of which can be found at http://www.worldserver.com/mm.mysql/
The following example shows how one might use servlet technology in a simple
shopping cart application. The product catalog will be stored in the database.
Items placed in the customer's cart will be stored in the HttpSession
object.
Setting up the database:
- First, create the database:
$ mysqladmin create testCart
Make sure that you have the appropriate permissions to create databases
and tables in your MySQL database.
- Create the table and import data.
$ mysql testCart < cart.sql
The ShoppingCart.java class displays a fictional product catalog
where the customer can select items to add to their "cart". When the customer is
done adding items to their cart, they can click on the "View Your Cart" link and
get an itemized list of each product they selected.
The "brains" of the servlet is contained within the doGet() method.
The cutomer's shopping cart is represented by a Java Hashtable. The key
of the Hashtable is the productID of the item and the value of the Hashtable
entry is the quantity of the products desired.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Hashtable cart;
PrintWriter out;
HttpSession session;
out = response.getWriter();
response.setContentType("text/html");
session = request.getSession(true);
String id = request.getParameter("id");
String command = request.getParameter("command");
String requestURI = request.getRequestURI();
cart = (Hashtable) session.getValue("cart");
if (cart == null) {
cart = new Hashtable();
}
out.println("<h1>Shopping Cart</h1>");
try {
if (command.equals("add")) {
Integer num = (Integer) cart.get(id);
if (num == null) { num = new Integer(0); }
cart.put(id, new Integer(num.intValue() + 1) );
printCatalog(out, requestURI);
} else if (command.equals("viewcart")) {
printCart(cart, out, requestURI);
} else {
printCatalog(out, requestURI);
}
} catch (NullPointerException e) {
printCatalog(out, requestURI);
}
session.putValue("cart", cart);
}
After declaring serveral objects, the the PrintWriter "out"
is obtained from the HttpServletResponse's getWriter() method, as
described previously. If the servlet were to return a binary file, like a
dynamically created GIF or JPEG for example, you would want to use the
ServletResponse's getOutputStream() method.
The next line,
session = request.getSession(true);
initiates a session in the servlet engine where information can be
stored to have a persistent state. The customer's shopping cart, represented by
the
Hashtable, will be stored in the HttpSession object. The boolean
parameter passed to the
getSession() method tells the servlet engine to
start a session if one hasn't already been started. If the parameter passed was
'false', then the servlet would return the already existing session object.
Otherwise, the getSession() method will return
null.
String id = request.getParameter("id");
String command = request.getParameter("command");
The next two lines demonstrate how to get values passed to your
servlet from HTML forms. The getParameter() doesn't differentiate if the form
data was passed in a GET request or a POST request. If the form parameter
doesn't exist, the method returns
null. Alternatively, you can use the
ServletRequest's getParameterNames() method to get an Enumeration of parameter
names you can iterate through with the getParameter() to get all of the form
names and values.
Next, the cart is instantiated.
cart = session.getValue("cart");
if (cart == null) {
cart = new Hashtable();
}
If the Hashtable cannot be retrieved from the session object with
the
HttpSession.getValue(String key) method, then one is instantiated
as a new Hashtable.
Now comes the logic of the servlet. The default behavior of the servlet is to
print display the product catalog. If the customer click's on the "Add to Cart"
hyperlink, the command "add" and the product ID of the item is passed to the
servlet. The value of the Hashtable entry with the productID as the key is
incremented, and the product catalog is again displayed. If the "View your Cart"
hyperlink is clicked, then the "viewcart" command is passed to the servlet and
the contents of the customer's cart is displayed.
Finally, after products have been added (optionally) to the the cart
Hashtable, it is put back into the session object, replacing the old cart.
JDBC
The product listing and cart content listing is generated
dynamically from the database.
public void init(ServletConfig config) throws ServletException {
super.init(config);
dbc = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
dbc =
DriverManager.getConnection("jdbc:mysql://localhost:3306/testCart?"
+ "user=dbUser&password=userPasswd");
} catch (Exception e) {
e.printStackTrace();
}
}
In the init() method, the database connection is initialized, and
will be available to the servlet for its lifetime. In the JSDK 2.0
specification, the
super.init(ServletConfig) method must
be the first command in the method. However, in version 2.1 of the
specification, this requirement has been fixed and is no longer necessary. If
you are going to be using mutltiple servlets accessing a database, a better
solution would be to use a database connection pool.
try {
Statement stmt = dbc.createStatement();
stmt.execute("select * from Products");
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
out.println("<tr>");
out.println("<td><b>" + rs.getString("name") + "</b><br>" +
rs.getString("description") + "</td>");
out.println("<td align=\"right\">" +
nf.format(rs.getDouble("price")) + "</td>");
out.println("<td><a href=\"" + requestURI + "?command=add&id=" +
String.valueOf(rs.getInt("productID")) +
"\">Add to Cart</a></td>");
out.println("</tr>");
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
The JDBC methods called in the printCatalog() and printCart()
methods are fairly straightforward; we simply create a
Statement from
the database connection, execute the SQL query, and then iterate through the
result set.
It is important to remember to free up the resources used in your servlet, as
multiple accesses can impact your server quite quickly. In the ShoppingCart.java
example statements and result sets are closed after every request, and the
database conncection is closed inside the servlet's destroy() method.