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;
@WebListener
public class ServletRequestLogger implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent event) {
System.out.println("request initialized, request by: " + event.getServletRequest().getRemoteAddr());
}
@Override
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="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.ServletRequestLogger</listener-class>
</listener>
</web-app>
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.