Pages

Saturday, January 26, 2008

Binding an Object into Session

Sometimes it is useful to know when an object is getting bound or unbound from a session object. For instance, in an application that binds a JDBC java.sql.Connection object to a session , it is important that the Connection be explicitly closed when the session is destroyed.

The javax.servlet.http.HttpSessionBindingListener interface handles this task. It includes two methods, valueBound() and valueUnbound(), that are called whenever the object that implements the interface is bound or unbound from a session, respectively. Each of these methods receives an HttpSessionBindingEvent object that provides the name of the object being bound/unbound and the session involved in the action. Here is an object that implements the HttpSessionBindingListener interface in order to make sure that a database connection is destroy.

below is the sample JDBC connection object binds to your Session.

/*
* SessionConnection.java
*/

import java.sql.*;
import javax.servlet.http.*;

/**
* @author amontejo
*/
public class SessionConnection implements HttpSessionBindingListener {

Connection connection;

/** Creates a new instance of SessionConnection */
public SessionConnection() {
this.connection = null;
}

public Connection getConection() {
return connection;
}

public void setConnection(Connection connection) {
this.connection = connection;
}

public void valueBound(HttpSessionBindingEvent event) {
if (connection != null) {
System.out.println("Binding a valid connection");
} else {
System.out.println("Binding a null connection");
}
}

public void valueUnbound(HttpSessionBindingEvent event) {
if (connection != null) {
System.out.println("Closing the bound connection as the session expires");
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}

As the Session expire the object will be closed too. You can set/check your session expiry in your web.xml.

<session-config>
<session-timeout>
30
</session-timeout>
<session-config>

-> means session expire within 30 minutes idle
see
HttpSessionBindingListener documentation here.
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpSessionBindingListener.html

No comments:

Post a Comment