Session Tracking

Problem

You want to keep track of one user across several servlet invocations within the same browser session.

Solution

Use an HttpSession object.

Discussion

HTTP was designed to be a stateless protocol: you would connect to a server, download a laboratory report, and that would be the end of it. Then people started getting clever, and began using it for interactive applications. For such purposes as a shopping cart in an online mall, and tracking answers during an online quiz or moves in an online game, the notion of an HTTP session has evolved to keep track of a particular browser. Sessions can be identified either by use of a cookie (see Section 18.4) or by a Session Identifier that is added to the URL. In either case the session ends when the user’s browser program exits, but will otherwise stick around for a long time (there is probably a major denial-of-service attack hidden in here, so beware).

Using a session is fairly simple within the Servlet API. You request the HttpSession object from the HttpRequest that is passed into your service( ) or doGet( )/doPost( ) method. The session object behaves rather like a Hashtable (see Section 7.7) except that the method names are putValue( ) and getValue( ). This allows you to store an arbitrary number of objects in the session and retrieve them later.

This program uses an HttpSession to keep track of a user’s responses during a quiz about Java. There are some 20 categories; once you pick a category, you can answer all ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.