ServletContextAttributeListener Example Use Case

This example explains how to use a ServletContextAttributeListener in a web application. This interface is used for receiving notification events about ServletContext attribute changes. In order to receive these notifications the ServletContextAttributeListener needs to be known by the ServletContext. This can be by using the @WebListener annotation, adding the listener to the servlet descriptor or programmatically adding a listener with .addListener() to the servlet context. In this example we use the @WebListener annotation.

ServletContextAttributeListener receives notifications for servlet context attribute changes

In order to listen to a attribute change in the servlet context we need to implement the javax.servlet.ServletContextAttributeListener interface. This interface lets us listen to the following events, the names speak for themselves.

  • attributeAdded()
  • attributeRemoved()
  • attributeReplaced()

To register a listener we can add the @WebListener, define the listener in the servlet descriptor (web.xml) or programatigally add it to the servlet context. In this example we choose to add the listener through the @WebListener annotation.

package com.memorynotfound;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ApplicationContextAttributeListener implements ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("attribute: " + event.getName() + " was added with value: " + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        System.out.println("attribute: " + event.getName() + " was removed with value: " + event.getValue());
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        System.out.println("attribute: " + event.getName() + " was replaced with value: " + event.getValue());
    }
}

Note: If you prefer the web.xml servlet descriptor over the @WebListener annotation you can add the context listener as follows:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

    <listener>
        <listener-class>com.memorynotfound.ApplicationContextAttributeListener</listener-class>
    </listener>
    
</web-app>

How does it work

Every time an attribute is added, replaced or removed the corresponding method is invoked. This allows us to track changes to certain attributes in our servlet context.

References

You may also like...