FAQ

Java

JSP

Servlet


Advertisement



When do I use HttpSessionListener?

The HttpSessionListener interface is used to monitor when sessions are created and destroyed on the application server. Its best practical use would be to track session use statistics for a server.

To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. This entry points the server to a class that will be called when a session is created or destroyed. The entry required is simple. All you need is a listener and listener-class element in the following format. The listener-class element must be a fully qualified class name.

<listener>
<listener-class>mypackage.MySessionListener</listener-class>
</listener>

The HttpSessionListener interface has two methods:

  • public void sessionCreated(HttpSessionEvent se) : Notification that a session was created.
  • public void sessionDestroyed(HttpSessionEvent se) : Notification that a session is about to be invalidated.

The following example demonstrates how these methods may be used:

package mypackage;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

public class MyHttpSessionListener implements HttpSessionListener
{
public void sessionCreated(HttpSessionEvent se)
{
HttpSession session = se.getSession();
System.out.print(getTime() + " (session) Created:");
System.out.println("ID=" + session.getId() + " MaxInactiveInterval=" + session.getMaxInactiveInterval());
}
public void sessionDestroyed(HttpSessionEvent se)
{
HttpSession session = se.getSession();
// session has been invalidated and all session data //(except Id)is no longer available
System.out.println(getTime() + " (session) Destroyed:ID=" + session.getId());
}
private String getTime()
{
return new Date(System.currentTimeMillis()).toString();
}
}

There is no distinct difference between session timeout and session invalidation from the perspective of the session object. Other HttpSession API methods may be used to determine timeout and invalidation values.

The HttpSessionListener and HttpSessionAttributeListener is defined in <listener> in your web.xml file. They are "application-wide", they manage all the session in your web-application! And they are instanticated by your web-container.

Even if your session attribute implements HttpSessionListener or HttpSessionAttributeListener, but you do not define that in web.xml, there is NO HttpSessionListener or HttpSessionAttributeListener instance in your web-application at all! (If you just create an HttpSessionListener instance by your own, it won't work because your web-application does not know at all, it only checks the web.xml).


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |