O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required