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;

public class ApplicationContextAttributeListener implements ServletContextAttributeListener {

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

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

    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=""
                   " version="3.1">


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.


You may also like...