Tuesday 21 August 2012

HttpSessionListener

A HttpSessionListener is used when you want to be notified that a Session has been created or destroyed.  This simple interface only has two methods,

    void sessionCreated(HttpSessionEvent httpSessionEvent);

    void sessionDestroyed(HttpSessionEvent httpSessionEvent);

These methods can easily be used to get or put items on the new session or perhaps set login, logout times in a log or database.

Web.xml

SessionListeners must be wired into the web.xml in the same way that filters are.  The syntax is very simple though,

    <listener>
        <description>sessionListener</description>
        <listener-class>my.package.MyListener</listener-class>
    </listener>


Getting the HttpSession

The HttpSessionEvent can be used to get the HttpSession itself simply with

    HttpSession session = sessionEvent.getSession();

Spring Integration

Normally there are spring beans that you want to use from within a HttpSessionListener.  However, as the listeners are not wired by spring but sorted out by the container you can't just add the listener to the spring context and expect it to work.  To use other spring beans you need to do the following,


            ApplicationContext ctx = WebApplicationContextUtils
                                              .getWebApplicationContext(session.getServletContext());
            MySpringBean mySpringBean = (MySpringBean) ctx.getBean("beanName");


Chaining

Another option is to create all of HttpSessionListeners and wire them up with spring as normal.  Then create a list of these as a spring bean itself.  Now use the code above to get this list of session listeners and loop through them.  These allows a single HttpSessionListener to bridge the gap to a whole load of listeners wired up by spring.


    <util:list id="sessionListenerChain" value-type="javax.servlet.http.HttpSessionListener">
        <ref bean="firstSessionListener" />
        <ref bean="secondSessionListener" />
    </util:list>


Both 'firstSessionListener' and 'secondSessionListener' are fully wired up using spring in the normally way allowing interaction with the other spring beans.  The actually HttpSessionListener wired into the web.xml file can then call for this util:list and loop through the session listeners to call them.

    List<HttpSessionListener> listenerChain = (List<HttpSessionListener>) ctx.getBean("sessionListenerChain");
    for (HttpSessionListener listener : listenerChain)
    {
        listener.sessionCreated(sessionEvent);
    }

Of course similar code can be used in the sessionDestroyed() method.











No comments:

Post a Comment