Sun Java System Web Server 7.0 Update 7 Developer's Guide to Java Web Applications

Binding Data to a Session

You can bind objects to sessions to make them available across multiple user interactions.

The following table shows the HttpSession methods that provide support for binding objects to the session object.

Table 6–3 HttpSession Methods

HttpSession Method  

Description  

getAttribute()

Returns the object bound to a given name in the session, or null if there is no such binding. 

getAttributeNames()

Returns an array of names of all attributes bound to the session. 

setAttribute()

Binds the specified object into the session with the given name. Any existing binding with the same name is overwritten. For an object bound into the session to be distributed, it must implement the serializable interface. 

removeAttribute()

Unbinds an object in the session with the given name. If there is no object bound to the given name, this method does nothing. 

Binding Notification with HttpSessionBindingListener

Some objects require you to know when they are placed in or removed from a session. To obtain this information, implement the HttpSessionBindingListener interface in those objects. When your application stores or removes data with the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, the Web Server notifies the object under consideration, through the HttpSessionBindingListener interface, that it is being bound into or unbound from the session.