views:

442

answers:

2

To track user activity history on a web application, I am attempting to save some session data to a database when the session is invalidated. My initial approach was to store the data on a javabean with a session scope and have it dump its data to the database through the finalize method.

I figured this wouldn't be a perfect solution due to the unpredictable behavior of finalize, but that it should work and eventually save the data. However, it turned out that this tactic does not reliably achieve the desired results - the data is often not logged even when the session is manually invalidated and the current user is switched.

What might be a better way to save data session data to a database without constantly updating it after every client action? Is there a way to call a specific method upon session invalidation?

A: 

An HttpSessionListener may help do what you're looking to do.

With this you can be notified of when a new session is created, or an old session is destroyed.

E.g.

Create a listener class:

public class MySessionListener implements HttpSessionListener {

  public void sessionCreated( HttpSessionEvent e ) {
    //...
  }

  public void sessionDestroyed( HttpSessionEvent e ) {
    //...
  }

}

Then register it in your web.xml

<listener>
  <listener-class>mypackage.MySessionListener</listener-class>
</listener>
jimr
This certainly helps but, given my design, it seems like a rather round about way of achieving the requirements. I'll hold out for another day see if any better suggestions come along, otherwise I'll give you credit for the solution.
dborba
+1  A: 

See for example Last wish taglib: http://www.servletsuite.com/servlets/lastwish.htm

Coldbeans Software
Perfect - this does exactly what I wanted. =D
dborba