The Session API
The interface declaration of HttpSession contains over a dozen methods in all. Minimally, an application will likely call three of these methods. The first of these is the getSession() method, which is used to either create a session object if one does not already exist or to associate a request with an existing session. In order to store information in the session object, the setAttribute() method is called, and the application retrieves information that is stored via a call to the getAttribute() method. Often overlooked in an application is the invalidate() method call. There should also be some provision in the application to invalidate the session object once the application no longer requires the session:
Unless configured to never do so, the web container will eventually invalidate the session object once the inactive interval for the session is reached. When the application explicitly invalidates the session, it reduces the overhead on the runtime of tracking sessions that are no longer required. You can also minimize the size of session objects prior to invalidation by removing attributes no longer required by explicitly calling the removeAttribute() method in the application.
Another constraint exists for applications that implement distributable sessions, which are sessions that can be handled by more than one web container, typically in order to provide for failover. In this case, all objects placed into HttpSession via the method must be serializable. WebSphere Application Server does provide for exceptions to this requirement for some J2EE objects that are not serializable:
The specifics on how WAS overcomes this restriction vary for each of these objects. Except for UserTransaction, which requires a WebSphere specific public wrapper object, the mechanism employed is transparent to the application.
It is best if all objects placed into HTTP session are serializable or you'll experience a java.io.NotSerializable Exception, as shown in Code Snippet 22-1. This provision ensures transparent deployment in both non-clustered and clustered environments, without requiring application changes for the latter. It's also important to note that it's not sufficient that the application simply implement the java.io.Serializable interface; the objects must actually be serializable, which is an important but subtle distinction that we'll return to later.