Welcome to my Tomcat tutorials website!

martedì 13 gennaio 2009

Tomcat session listener example

As part of Servlet 2.3 specification, we can now make use of session creation and destruction events. Our listener object will be called every time a session is created or destroyed by the server.

You can use two interfaces as listener for your Session:

  • HttpSessionListener triggers the listener when a new session is created or destroyed
  • HttpSessionBindingListener triggers the listener when an Object is bound/unbound from the Session
HttpSessionListener example:

package com.sample;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class SessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {

if(activeSessions > 0)
activeSessions--;
}



public static int getActiveSessions() {
return activeSessions;
}

}

As you can see, all you have to do is implementing two methods: sessionCreated() method
will be called by the server every time a session is created and sessionDestroyed() method will be called every time a session is invalidated or destroyed.

In order to activate the listener, you have to configure it in your web.xml

<listener>
<listener-class>
com.sample.SessionCounter
</listener-class>
</listener>

HttpSessionBindingListener example :

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

public class JDBCQueryBean implements HttpSessionBindingListener
{
  public void JDBCQueryBean() {   }

  private Connection conn = null;

  private void runQuery() {
    StringBuffer sb = new StringBuffer();
    Statement stmt = null;
    ResultSet rset = null;
    try {
      if (conn == null) {
        DriverManager.registerDriver(new .OracleDriver());
        conn = DriverManager.getConnection("jdbc:oracle:oci8:@",
                                           "scott", "tiger");

      }
   
      stmt = conn.createStatement();
      rset = stmt.executeQuery ("SELECT * from ....");
  
    } catch (SQLException e) {
       e.printStackTrace();
  }
    finally {
      try {
        if (rset != null) rset.close();
        if (stmt != null) stmt.close();
      }
      catch (SQLException ignored) {}
    }
  }

  public void valueBound(HttpSessionBindingEvent event) {
    // do nothing -- the session-scoped bean is already bound
  }

  public synchronized void valueUnbound(HttpSessionBindingEvent event) {
    try {
      if (conn != null) conn.close();
    }
    catch (SQLException ignored) {}
  }
}

This is a sample code for JDBCQueryBean, a JavaBean that implements the HttpSessionBindingListener interface. The Connection object is bound into the Session and the listener takes care to close the connection as soon as the Session expires.

Nessun commento:

Posta un commento