ServletRequestListener Example Use Case

This example explains how to use a ServletRequestListener in a web application. This interface is used for receiving notification events about requests coming into and going out of scope of a web application. Notifications will be generated when a request is first comming into scope and when it get out of scope. The ServletRequestListener can be registerd by @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.

ServletRequestListener receives notifications for ServletRequest init and destroy

In order to listen to the lifecyle event of initialization or destroying of a ServletRequest we need to implement the javax.servlet.ServletRequestListener interface. This interface lets us listen to the following events, the names speak for themselves.

  • requestInitialized()
  • requestDestroyed()

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.*;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

public class ServletRequestLogger implements ServletRequestListener {

    public void requestInitialized(ServletRequestEvent event) {
        System.out.println("request initialized, request by: " + event.getServletRequest().getRemoteAddr());

    public void requestDestroyed(ServletRequestEvent event) {
        System.out.println("request destroyed");


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

When a ServletRequest is created for the first time the requestInitialized() is called. When the ServletRequest is out of scope and therefore destroyed the requestDestroyed() will be invoked.


You may also like...