How do I use Session Tracking? That is, how can I maintain "session scope data" between servlets in the same application?

Alex Chaffee

Session Tracking is one of the most powerful features of Servlets and JSP. Basically, the servlet engine takes care of using Cookies in the right way to preserve state across successive requests by the same user. Your servlet just needs to call a single method (getSession) and it has access to a persistent hashtable of data that's unique to the current user. Way cool.

See section 2.3 of the Servlet Essentials tutorial (http://www.novocode.com/doc/servlet-essentials/) . Also see The Session Tracking API (http://webreview.com/wr/pub/1999/01/08/bookshelf/) , excerpted from Java Servlet Programming (http://www.oreilly.com/catalog/jservlet/) by Jason Hunter (http://webreview.com/wr/pub/au/Hunter_Jason).

A point I haven't seen emphasized enough is that you should only add objects that are serializable to an <mono>HttpSession</mono>. Specifically, a JDBC Connection object is not serializable, so should not be added to the session (despite the example in Jason Hunter's otherwise admirable Java Servlet Programming). If you'd like to associate a connection with a session, then store some arbitrary, unique handle in the session, then use that to key off your own hashtable of connections. (Make sure upon retrieval that the returned connection is not null, and if it is, create a new connection!)

The reason is that sessions may, at the whim of the server, be swapped out to disk, in order to save memory or reboot the server. This behavior can be disabled by setting a configuration parameter in your server or servlet engine. (I can't remember offhand what these are -- please email me if you know.) From the spec:

Some servlet engine implementations will persist session data or distribute it amongst multiple network nodes. For an object bound into the session to be distributed or persisted to disk, it must implement the Serializable interface.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.