Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

2.10 Session Tracking

This section briefly introduces the servlet session-tracking API, which keeps track of visitors as they move around at your site. For additional details and examples, see Chapter 9 of Core Servlets and JavaServer Pages (in PDF at http://www.moreservlets.com).

The Need for Session Tracking

HTTP is a "stateless" protocol: each time a client retrieves a Web page, it opens a separate connection to the Web server. The server does not automatically maintain contextual information about a client. Even with servers that support persistent (keep-alive) HTTP connections and keep a socket open for multiple client requests that occur close together in time, there is no built-in support for maintaining contextual information. This lack of context causes a number of difficulties. For example, when clients at an online store add an item to their shopping carts, how does the server know what's already in the carts? Similarly, when clients decide to proceed to checkout, how can the server determine which previously created shopping carts are theirs?

There are three typical solutions to this problem: cookies, URL rewriting, and hidden form fields. The following subsections quickly summarize what would be required if you had to implement session tracking yourself (without using the built-in session tracking API) each of the three ways.

Cookies

You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. For example, a servlet could do something like the following:

String sessionID = makeUniqueString();
Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sessionID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sessionID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);

Then, in later requests the server could use the globalTable hash table to associate a session ID from the JSESSIONID cookie with the sessionInfo hash table of data associated with that particular session. This is an excellent solution and is the most widely used approach for session handling. Still, it is nice that servlets have a higher-level API that handles all this plus the following tedious tasks:

  • Extracting the cookie that stores the session identifier from the other cookies (there may be many cookies, after all).

  • Setting an appropriate expiration time for the cookie.

  • Associating the hash tables with each request.

  • Generating the unique session identifiers.

URL Rewriting

With this approach, the client appends some extra data on the end of each URL that identifies the session, and the server associates that identifier with data it has stored about that session. For example, with http://host/path/file.html;jsessionid=1234, the session information is attached as jsessionid=1234. This is also an excellent solution and even has the advantage that it works when browsers don't support cookies or when the user has disabled them. However, it has most of the same problems as cookies, namely, that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL that references your site and is returned to the user (even by indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.

Hidden Form Fields

HTML forms can have an entry that looks like the following:

<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

This entry means that, when the form is submitted, the specified name and value are included in the GET or POST data. This hidden field can be used to store information about the session but has the major disadvantage that it only works if every page is dynamically generated by a form submission. Thus, hidden form fields cannot support general session tracking, only tracking within a specific series of operations.

Session Tracking in Servlets

Servlets provide an outstanding technical solution: the HttpSession API. This high-level interface is built on top of cookies or URL rewriting. All servers are required to support session tracking with cookies, and many have a setting that lets you globally switch to URL rewriting. In fact, some servers use cookies if the browser supports them but automatically revert to URL rewriting when cookies are unsupported or explicitly disabled.

Either way, the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store arbitrary objects that are associated with each session.

The Session-Tracking API

Using sessions in servlets is straightforward and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions. Finally, if you return any URLs to the clients that reference your site and URL rewriting is being used, you need to attach the session information to the URLs.

Looking Up the HttpSession Object Associated with the Current Request

You look up the HttpSession object by calling the getSession method of HttpServletRequest. Behind the scenes, the system extracts a user ID from a cookie or attached URL data, then uses that as a key into a table of previously created HttpSession objects. But this is all done transparently to the programmer: you just call getSession. If getSession returns null, this means that the user is not already participating in a session, so you can create a new session. Creating a new session in this case is so commonly done that there is an option to automatically create a new session if one doesn't already exist. Just pass true to getSession. Thus, your first step usually looks like this:

HttpSession session = request.getSession(true);

If you care whether the session existed previously or is newly created, you can use isNew to check.

Looking Up Information Associated with a Session

HttpSession objects live on the server; they're just automatically associated with the client by a behind-the-scenes mechanism like cookies or URL rewriting. These session objects have a built-in data structure that lets you store any number of keys and associated values. In version 2.1 and earlier of the servlet API, you use ses_sion.getValue("attribute") to look up a previously stored value. The return type is Object, so you have to do a typecast to whatever more specific type of data was associated with that attribute name in the session. The return value is null if there is no such attribute, so you need to check for null before calling methods on objects associated with sessions.

In versions 2.2 and 2.3 of the servlet API, getValue is deprecated in favor of getAttribute because of the better naming match with setAttribute (in version 2.1, the match for getValue is putValue, not setValue).

Here's a representative example, assuming ShoppingCart is some class you've defined to store information on items being purchased.

HttpSession session = request.getSession(true);
ShoppingCart cart =
 (ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) { // No cart already in session
 cart = new ShoppingCart();
 session.setAttribute("shoppingCart", cart);
}
doSomethingWith(cart);

In most cases, you have a specific attribute name in mind and want to find the value (if any) already associated with that name. However, you can also discover all the attribute names in a given session by calling getValueNames, which returns an array of strings. This method was your only option for finding attribute names in version 2.1, but in servlet engines supporting versions 2.2 and 2.3 of the servlet specification, you can use getAttributeNames. That method is more consistent in that it returns an Enumeration, just like the getHeaderNames and getParameterNames methods of HttpServletRequest.

Although the data that was explicitly associated with a session is the part you care most about, some other pieces of information are sometimes useful as well. Here is a summary of the methods available in the HttpSession class.

public Object getAttribute(String name)
public Object getValue(String name) [deprecated]

These methods extract a previously stored value from a session object. They return null if no value is associated with the given name. Use getValue only if you need to support servers that run version 2.1 of the servlet API. Versions 2.2 and 2.3 support both methods, but getAttribute is preferred and getValue is deprecated.

public void setAttribute(String name, Object value)
public void putValue(String name, Object value) [deprecated]

These methods associate a value with a name. Use putValue only if you need to support servers that run version 2.1 of the servlet API. If the object supplied to setAttribute or putValue implements the HttpSessionBindingListener interface, the object's valueBound method is called after it is stored in the session. Similarly, if the previous value implements HttpSessionBindingListener, its valueUnbound method is called.

public void removeAttribute(String name)
public void removeValue(String name) [deprecated]

These methods remove any values associated with the designated name. If the value being removed implements HttpSessionBindingListener, its valueUnbound method is called. Use removeValue only if you need to support servers that run version 2.1 of the servlet API. In versions 2.2 and 2.3, removeAttribute is preferred, but removeValue is still supported (albeit deprecated) for backward compatibility.

public Enumeration getAttributeNames()
public String[] getValueNames() [deprecated]

These methods return the names of all attributes in the session. Use getValueNames only if you need to support servers that run version 2.1 of the servlet API.

public String getId()

This method returns the unique identifier generated for each session. It is useful for debugging or logging.

public boolean isNew()

This method returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.

public long getCreationTime()

This method returns the time in milliseconds since midnight, January 1, 1970 (GMT) at which the session was first built. To get a value useful for printing, pass the value to the Date constructor or the setTimeIn_Millis method of GregorianCalendar.

public long getLastAccessedTime()

This method returns the time in milliseconds since midnight, January 1, 1970 (GMT) at which the session was last sent from the client.

public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)

These methods get or set the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never time out. Note that the timeout is maintained on the server and is not the same as the cookie expiration date, which is sent to the client. See Section 5.10 (Controlling Session Timeouts) for instructions on changing the default session timeout interval.

public void invalidate()

This method invalidates the session and unbinds all objects associated with it. Use this method with caution; remember that sessions are associated with users (i.e., clients), not with individual servlets or JSP pages. So, if you invalidate a session, you might be destroying data that another servlet or JSP page is using.

Associating Information with a Session

As discussed in the previous section, you read information associated with a session by using getAttribute. To specify information, use setAttribute. To let your values perform side effects when they are stored in a session, simply have the object you are associating with the session implement the HttpSessionBindingListener interface. That way, every time setAttribute (or putValue) is called on one of those objects, its valueBound method is called immediately afterward.

Be aware that setAttribute replaces any previous values; if you want to remove a value without supplying a replacement, use removeAttribute. This method triggers the valueUnbound method of any values that implement HttpSessionBindingListener.

Following is an example of adding information to a session. You can add information in two ways: by adding a new session attribute (as with the first bold line in the example) or by augmenting an object that is already in the session (as in the last line of the example).

HttpSession session = request.getSession(true);
ShoppingCart cart =
 (ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) { // No cart already in session
 cart = new ShoppingCart();
 session.setAttribute("shoppingCart", cart);
}
addSomethingTo(cart);

Terminating Sessions

Sessions automatically become inactive when the amount of time between client accesses exceeds the interval specified by getMaxInactiveInterval. When this happens, any objects bound to the HttpSession object automatically get unbound. Then, your attached objects are automatically notified if they implement the HttpSessionBindingListener interface.

Rather than waiting for sessions to time out, you can explicitly deactivate a session with the session's invalidate method.

Encoding URLs Sent to the Client

If you are using URL rewriting for session tracking and you send a URL that references your site to the client, you need to explicitly add the session data. There are two possible places where you might use URLs that refer to your own site.

The first is where the URLs are embedded in the Web page that the servlet generates. These URLs should be passed through the encodeURL method of HttpServletResponse. The method determines if URL rewriting is currently in use and appends the session information only if necessary. The URL is returned unchanged otherwise.

Here's an example:

String originalURL = someRelativeOrAbsoluteURL;
String encodedURL = response.encodeURL(originalURL);
out.println("<A HREF=\"" + encodedURL + "\">...</A>");

The second place you might use a URL that refers to your own site is in a sendRedirect call (i.e., placed into the Location response header). In this second situation, different rules determine whether session information needs to be attached, so you cannot use encodeURL. Fortunately, HttpServletResponse supplies an encodeRedirectURL method to handle that case. Here's an example:

String originalURL = someURL; 
String encodedURL = response.encodeRedirectURL(originalURL);
response.sendRedirect(encodedURL);

Since you often don't know if your servlet will later become part of a series of pages that use session tracking, it is good practice to plan ahead and encode URLs that reference your own site.

A Servlet Showing Per-Client Access Counts

Listing 2.19 presents a simple servlet that shows basic information about the client's session. When the client connects, the servlet uses request.getSession(true) either to retrieve the existing session or, if there was no session, to create a new one. The servlet then looks for an attribute of type Integer called accessCount. If it cannot find such an attribute, it uses 0 as the number of previous accesses. This value is then incremented and associated with the session by setAttribute. Finally, the servlet prints a small HTML table showing information about the session. Figures 2–17 and 2–18 show the servlet on the initial visit and after the page was reloaded several times.

Figure 2-17Figure 2–17 First visit by client to ShowSession servlet.


Figure 2-18Figure 2–18 Eleventh visit to ShowSession servlet. Access count is independent of number of visits by other clients.


Listing 2.19 ShowSession.java

package moreservlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

/** Simple example of session tracking. */

public class ShowSession extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
  HttpSession session = request.getSession(true);
  String heading;
  Integer accessCount =
   (Integer)session.getAttribute("accessCount");
  if (accessCount == null) {
   accessCount = new Integer(0);
   heading = "Welcome, Newcomer";
  } else {
   heading = "Welcome Back";
   accessCount = new Integer(accessCount.intValue() + 1);
  }
  session.setAttribute("accessCount", accessCount); 
  out.println(ServletUtilities.headWithTitle(title) +
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
        "<H2>Information on Your Session:</H2>\n" +
        "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
        "<TR BGCOLOR=\"#FFAD00\">\n" +
        " <TH>Info Type<TH>Value\n" +
        "<TR>\n" +
        " <TD>ID\n" +
        " <TD>" + session.getId() + "\n" +
        "<TR>\n" +
        " <TD>Creation Time\n" +
        " <TD>" +
        new Date(session.getCreationTime()) + "\n" +
        "<TR>\n" +
        " <TD>Time of Last Access\n" +
        " <TD>" +
        new Date(session.getLastAccessedTime()) + "\n" +
        "<TR>\n" +
        " <TD>Number of Previous Accesses\n" +
        " <TD>" + accessCount + "\n" +
        "</TABLE>\n" +
        "</BODY></HTML>");

 }

 /** Handle GET and POST requests identically. */
 
 public void doPost(HttpServletRequest request,
           HttpServletResponse response)
   throws ServletException, IOException {
  doGet(request, response);
 }
}

A Simplified Shopping Cart Application

Core Servlets and JavaServer Pages (available in PDF at http://www.moreservlets.com) presents a full-fledged shopping cart example. Most of the code in that example is for automatically building the Web pages that display the items and for the shopping cart itself. Although these application-specific pieces can be somewhat complicated, the basic session tracking is quite simple. This section illustrates the fundamental approach to session tracking, but without a full-featured shopping cart.

Listing 2.20 shows an application that uses a simple ArrayList (the Java 2 platform's replacement for Vector) to keep track of all the items each user has previously purchased. In addition to finding or creating the session and inserting the newly purchased item (the value of the newItem request parameter) into it, this example outputs a bulleted list of whatever items are in the "cart" (i.e., the ArrayList). Notice that the code that outputs this list is synchronized on the ArrayList. This precaution is worth taking, but you should be aware that the circumstances that make synchronization necessary are exceedingly rare. Since each user has a separate session, the only way a race condition could occur is if the same user submits two purchases very close together in time. Although unlikely, this is possible, so synchronization is worthwhile.

Listing 2.20 ShowItems.java

package moreservlets; 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.ArrayList; 
import moreservlets.*; 

/** Servlet that displays a list of items being ordered.
 * Accumulates them in an ArrayList with no attempt at
 * detecting repeated items. Used to demonstrate basic
 * session tracking.
 */

public class ShowItems extends HttpServlet {
 public void doGet(HttpServletRequest request,
          HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession(true);
  ArrayList previousItems =
   (ArrayList)session.getAttribute("previousItems");
  if (previousItems == null) {
   previousItems = new ArrayList();
   session.setAttribute("previousItems", previousItems);
  }
  String newItem = request.getParameter("newItem");
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  String title = "Items Purchased";
out.println(ServletUtilities.headWithTitle(title) +
        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
        "<H1>" + title + "</H1>");
  synchronized(previousItems) {
   if (newItem != null) {
    previousItems.add(newItem);
   }
   if (previousItems.size() == 0) {
    out.println("<I>No items</I>");
   } else {
    out.println("<UL>");
    for(int i=0; i<previousItems.size(); i++) {
     out.println("<LI>" + (String)previousItems.get(i));
    }
    out.println("</UL>");
   }
  }
  out.println("</BODY></HTML>");
 }
}

Listing 2.21 shows an HTML form that collects values of the newItem parameter and submits them to the servlet. Figure 2–19 shows the result of the form; Figures 2–20 and 2–21 show the results of the servlet before visiting the order form and after visiting the order form several times, respectively.

Figure 2-19Figure 2–19 Front end to the item display servlet.


Figure 2-20Figure 2–20 The item display servlet before any purchases are made.


Figure 2-21Figure 2–21 The item display servlet after a few small purchases are made.


Listing 2.21 OrderForm.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
 <TITLE>Order Form</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Order Form</H1>
<FORM ACTION="/servlet/moreservlets.ShowItems">
 New Item to Order: 
 <INPUT TYPE="TEXT" NAME="newItem" VALUE="yacht"><BR>
 <CENTER>
  <INPUT TYPE="SUBMIT" VALUE="Order and Show All Purchases">
 </CENTER>
</FORM>
</BODY>
</HTML>
  • + Share This
  • 🔖 Save To Your Account