Metawerx Java Hosting Small Logo

Context Listener

A context listener receives notifications when the web application (ie: the context) is starting up or shutting down.

Creating a ContextListener

To create a Context Listener, create a class which implements the ServletContextListener interface.

This involves implementation of the following two methods:

public void contextInitialized(ServletContextEvent servletContextEvent);
public void contextDestroyed(ServletContextEvent servletContextEvent);

Each listener class must also have a public constructor taking no arguments.

contextInitialized()

This method is called whenever the application starts up.

contextDestroyed()

This method is called whenever the application is shutting down.

ServletContext

The ServletContext is passed to both of the above methods in the ServletContextEvent object.

It can be retrieved as follows:

ServletContext servletContext = servletContextEvent.getServletContext();

This object has setAttribute(), getAttribute() and removeAttribute() methods which can be used to store context-specific information.

Full Example

import javax.servlet.*;

public final class MyContextListener
implements ServletContextListener {

    public MyContextListener() {
    }

    public void contextInitialized(ServletContextEvent servletContextEvent) {

        // Get the context
        ServletContext servletContext = servletContextEvent.getServletContext();

        // Set a context attribute
        try {
            System.out.println("[MyContextListener] Application X is starting");
            servletContext.setAttribute("foo""bar");
        catch (Exception e) {
            System.out.println("[MyContextListener] Error setting context attribute: " + e.getMessage());
        }
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

        // Get the context
        ServletContext servletContext = servletContextEvent.getServletContext();

        // Output the context variable we set earlier
        System.out.println("[MyContextListener] Application X is shutting down");
        System.out.println("[MyContextListener] Value of foo is: " + servletContext.getAttribute("foo"));

        // Clean up (not really necessary as the context is being destroyed, but let's be neat)
        servletContext.removeAttribute("foo");
    }
}

Adding the Context Listener to web.xml

Add the above class to WEB-INF/classes, and add the following in web.xml to activate our new ContextListener.

<listener>
    <listener-class>MyContextListener</listener-class>
</listener>

Note that the above class was not put in a package, so no package name is specified in the <listener-class> tag.

Other Listener Examples

navigation
metawerx specific
search
Share
tools
help

referring pages
Valid XHTML 1.0 Transitional

Share