Thursday, 12 June 2014

Servlets : HttpSessionAttributeListener Demo

Master Core Java & Servlets!

Subscribe to Ram N Java for beginner-friendly coding walkthroughs, session management tutorials, and hands-on Java guides!

🔔 Subscribe to Ram N Java

What is HttpSessionAttributeListener?

In Java web applications, managing state across multiple HTTP requests typically revolves around attributes bound to the user's session. The HttpSessionAttributeListener interface (from the javax.servlet.http package) enables developers to monitor and react to lifecycle changes of attributes within an HttpSession.

Whenever a servlet or JSP adds an attribute, removes an attribute, or replaces an existing attribute in a user session, the container triggers corresponding callback methods on any registered listener. This provides a central location to audit user activity, log session updates, and synchronize session-scoped resources.

Core Lifecycle Callback Methods

The HttpSessionAttributeListener interface provides three key methods that receive an HttpSessionBindingEvent:

  • attributeAdded(HttpSessionBindingEvent se): Triggered when an attribute is first bound to a session using session.setAttribute(name, value).
  • attributeRemoved(HttpSessionBindingEvent se): Triggered when an attribute is unbound from a session using session.removeAttribute(name).
  • attributeReplaced(HttpSessionBindingEvent se): Triggered when an existing session attribute is overwritten with a new value for an identical attribute name.
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("Session Attribute Added: " + se.getName() + " = " + se.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        System.out.println("Session Attribute Removed: " + se.getName());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        System.out.println("Session Attribute Replaced: " + se.getName() + " (Old Value: " + se.getValue() + ")");
    }
}

Key Advantages of Using HttpSessionAttributeListener

  • Session State Auditing: Easily record when crucial attributes (like user authentication tokens, cart states, or permissions) are modified.
  • Decoupled Architecture: Keep tracking, logging, and security validation routines separate from business servlets.
  • Easy Setup: Configure globally using the @WebListener annotation or register via web.xml.

Recommended Related Tutorials

Continue exploring servlet listeners and session handling with these tutorials from Ram N Java:


Click here to watch in Youtube : https://www.youtube.com/watch?v=9ciciMjc8es

Click the below Image to Enlarge

HttpSessionAttributeListenerDemo Project Dir Structure

HttpSessionAttributeTestServlet.java
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class HttpSessionAttributeTestServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("-----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------");
    }

    public void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        response.setContentType("text/html");

        HttpSession httpSession = request.getSession();

        sleep();

        httpSession.setAttribute("CompanyName", "Wipro");

        sleep();

        httpSession.setAttribute("CompanyName", "Infosys");

        sleep();

        httpSession.removeAttribute("CompanyName");

    }

    private void sleep()
    {
        try
        {
            Thread.sleep(10000);
        }
        catch( InterruptedException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void destroy()
    {
        System.out.println("-----------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("-----------------------------------------");
    }

}

MyHttpSessionAttributeListener.java
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class MyHttpSessionAttributeListener implements
        HttpSessionAttributeListener
{

    @Override
    public void attributeAdded(
            HttpSessionBindingEvent httpSessionBindingEvent )
    {
        System.out.println("\n###################################\n");

        System.out.println("attributeAdded method has been called in "
                + this.getClass().getName());

        System.out.println("Newly added Attribute Name ="
                + httpSessionBindingEvent.getName() + ",value = "
                + httpSessionBindingEvent.getValue());

        System.out.println("\n#####################################\n");

        /*
         * if particular Attribute is added, based on that if you want to
         * perform any operation then you can do it here.
         */

    }

    @Override
    public void attributeRemoved(
            HttpSessionBindingEvent httpSessionBindingEvent )
    {
        System.out.println("\n###################################\n");

        System.out.println("attributeRemoved method has been called in "
                + this.getClass().getName());

        System.out.println("Removed Attribute Name ="
                + httpSessionBindingEvent.getName() + ",value = "
                + httpSessionBindingEvent.getValue());

        System.out.println("\n###################################\n");

        /*
         * if particular Attribute is Removed, based on that if you want to
         * perform any operation then you can do it here.
         */

    }

    @Override
    public void attributeReplaced(
            HttpSessionBindingEvent httpSessionBindingEvent )
    {
        System.out.println("\n###################################\n");

        System.out.println("attributeReplaced method has been called in "
                + this.getClass().getName());

        System.out.println("Replaced Attribute Name ="
                + httpSessionBindingEvent.getName() + ",value = "
                + httpSessionBindingEvent.getValue());

        System.out.println("\n###################################\n");

        /*
         * if particular Attribute is Replaced, based on that if you want to
         * perform any operation then you can do it here.
         */

    }

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
  <display-name>HttpSessionAttributeListenerDemo</display-name>
  <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
  <servlet>
    <servlet-name>HttpSessionAttributeTestServlet</servlet-name>
    <servlet-class>HttpSessionAttributeTestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HttpSessionAttributeTestServlet</servlet-name>
    <url-pattern>/listenerTest</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>MyHttpSessionAttributeListener</listener-class>
  </listener>
</web-app>

index.html
<html>
<body>
    <a href="listenerTest">listenerTest</a>
</body>
</html>

Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download HttpSessionAttributeListenerDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/HttpSessionAttributeListenerDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • 1 comment:

    Tutorials