Home > Articles > Programming > Java

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>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020