Return to Servlets index

Session Tracking

Imagine that a client calls an 'add to cart' servlet which adds the user's choice to a 'shopping cart' - and later another item is added. Where is the cart (item list)? And how does the servlet know it is the same client? When a servlet handles a client request with a response, that's it; there is no persistent connection between a client and servlet. However, through the use of sessions and cookies, it can seem to the client that a persistent connection exists.

Session tracking is a mechanism that servlets use to 'maintain state' about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

Sessions are shared among the servlets accessed by a client. This is convenient for applications made up of multiple servlets. All servlets on the same server have access to the user's session.


How to use session tracking

  • Get an HttpSession object for the user.

    The getSession(boolean create) method of the HttpServletRequest object returns a user's session. When you call this method with its create argument set to true, the implementation will create a new session object if one does not already exist. You must call getSession before any output is written to the response (if you respond using a Writer, then you must call getSession before accessing the Writer, not just before sending any response data.)  

  • Store or get data from the HttpSession object.
     
  • Invalidate the session if and when required (optional).

    A user's session can be invalidated programatically or, depending on where the servlet is running, automatically. (Most web servers automatically invalidate a session when there have been no page requests in some period of time, usually between 30 minutes and 2 hours). You can set the Kinabaloo Web Server to automatically invalidate sessions after a period of inactivity equal to 2, 10 or 30 minutes; the default value is 2 minutes, which is probably best for the development environment. To invalidate a session means to remove the HttpSession object and its values from the server.

    To programatically invalidate a session, use the session's invalidate() method.

The HttpSession interface provides methods that store and return :

  • Standard session properties, such as a session identifier.
     
  • Application data, which is stored as name-value pairs, where the name is a String and the value is an object in the Java programming language (this is like java.util.Dictionary). Because multiple servlets have access to a user's session, you could adopt a naming convention for organizing the names associated with application data. This can avoid servlets accidentally overwriting each other's values during the session. One such convention is servletname.name where servletname is the full name of the servlet, including its packages. For example, com.acme.WidgetServlet.state is a cookie with the servletname com.acme.WidgetServlet and the name state. However, it is also common for servlets to share such application data.

Because an object can be stored as a session attribute, the following example keeps track of the books that a user has ordered within an object of type ShoppingCart. Each book that a user orders is stored in the shopping cart as a ShoppingCartItem object.

 

An example

public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the current session or create a new one :
HttpSession session = request.getSession(true);
// Get the cart from the session :
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
...
// If no cart (perhaps because session is new), create one and add to session :
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
// If the user wants to add a book, add it and print the result
String bookToAdd = request.getParameter("Buy");
if (bookToAdd != null) {
BookDetails book = database.getBookDetails(bookToAdd);
cart.add(bookToAdd, book);
out.println("<p>You just added " + book.getTitle() + "to your shopping cart.</p>");
...
}
}

 

Return to Servlets index