Sessions

Sessions are important in eCommerce Web programming because they can be tracked. Let's begin with HTTP which is a stateless protocol. You don't have any way to store information that you need as the programmer in the protocol itself. This is very pertinent in, for example, an online store application. The Web server, via HTTP, cannot keep track of the user's online shopping cart. So how do you store information in a Web application?

A session is a way of identifying the user even through multiple page requests; something that HTTP doesn't have a mechanism to do. A session resides on the server so it handles the actual creation of the session for you assigning a unique ID to each session. Your job is to associate that session with the client who is making the HTTP request. This is normally implemented in one of two ways.

Cookies--The first way, and probably the most common, is to use a Cookie. In the Cookie, you can store information about the session that can be used later to identify the user. But be careful about what information you store in the Cookie. You should never store sensitive information like username, passwords, or credit card numbers.

This is an excellent solution because you have a Cookie interface in the package javax.servlet.http.cookie to use for your advantage. Normally, you would store the session ID inside the Cookie, and you can use the interface to request the Cookie and its attributes that are of interest to you.

URL Rewriting--Use URL rewriting to append information about the session to the URL allowing the server to identify which session belongs to the user. This is also an excellent way of implementing session tracking because this still allows you to track the user's session even if the user has disabled Cookies.

Session Tracking API

Java has provided an easy to use Session tracking API. It basically involves five tasks.

  1. Lookup the Session ID from the Cookie or URL associated with a specific user.

  2. Create a new Session if necessary.

  3. Lookup information associated with a Session.

  4. Storing information about a Session.

  5. Discarding a Session when it is completed.

Here are some common methods of the Session Tracking API. The methods are straightforward.

getID() - returns the Session ID
isNew() - returns true if the Session is new to the browser
getCreationTime() - returns the time the particular Session was created
getLastAccessedTime() - returns the time the Session was last accessed
setAttribute() - associates a value with a Session
getAttribute() - returns a value of an associated attribute

For more information and exact method signatures, see http://java.sun.com.

download sample files
Previous blank Table of Contents blank Next