Presents your JAVA E-NEWSLETTER for September 23, 2002 <-------------------------------------------> BIND AN OBJECT TO THE HTTPSESSION Sometimes we want to create an object, maybe as a resource or cache, that will last for the lifetime of a user's servlet or jsp session. This can be a problem if we also want that object to be available from another location. We don't want the object to get garbage collected when and if the session is terminated. We can prevent this problem by implementing the HttpSessionBindingListener. Here's a simple example (try/catches are ignored): public class SomeObject implements HttpSessionBindingListener { private Connection someDbConnection = null; .... various bits of code .... public void valueBound(HttpSessionBindingEvent event) { // open the Connection this.someDbConnection = .... } public void valueUnbound(HttpSessionBindingEvent event) { // close the Connection this.someDbConnection.close(); } } Binding this object to the session is so easy it requires no work. All we have to do is place the object in the session. If an object placed in the session implements HttpSessionBindingListener, then the session automatically makes it a listener and will notify it when bound and unbound. By implementing HttpSessionBindingListener, we can fully place our objects into the session's scope, knowing that even their creation and destruction in that scope can be monitored. ----------------------------------------