Showing posts with label ServletRequestListener. Show all posts
Showing posts with label ServletRequestListener. Show all posts

Saturday, 14 June 2014

Servlets : ServletRequestListener Demo

Master Core Java & Servlets!

Subscribe to Ram N Java for beginner-friendly coding walkthroughs, request lifecycle listeners, and hands-on Java guides!

🔔 Subscribe to Ram N Java

What is ServletRequestListener?

In Java web applications, the ServletRequestListener interface (from the javax.servlet package) is used to monitor the lifecycle of incoming client HTTP requests.

Whenever a request enters the web application and comes into scope, or when it leaves the scope after the response is generated, the servlet container notifies the registered listener. This makes it an ideal place to capture incoming IP addresses, measure request processing duration, log diagnostic information, or set up request-scoped resources.

Lifecycle Callback Methods

The ServletRequestListener interface defines two core methods that run for every client request:

  • requestInitialized(ServletRequestEvent sre): Triggered by the container when an incoming request is initialized and about to enter the first servlet or filter in the chain.
  • requestDestroyed(ServletRequestEvent sre): Triggered when the request has completed its processing, the response has been handled, and the request object is about to be reclaimed.
@WebListener
public class LoggingRequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletRequest request = sre.getServletRequest();
        System.out.println("Request initialized from IP: " + request.getRemoteAddr());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("Request processed and destroyed successfully.");
    }
}

Key Benefits of ServletRequestListener

  • Request Auditing & Monitoring: Easily record timestamps, client IP addresses, and request frequency across all application endpoints.
  • Decoupled Architecture: Completely decouples request-level lifecycle tracking and performance telemetry from individual business servlets.
  • Simple Configuration: Can be activated globally with a simple @WebListener annotation or configured in web.xml.

Recommended Related Tutorials

Continue exploring servlet listeners and web architecture with these tutorials from Ram N Java:


Click here to watch in Youtube : https://www.youtube.com/watch?v=48HCaqLXr5M

Click the below Image to Enlarge

ServletRequestListenerDemo Project Dir Structure

HitCountServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HitCountServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("-----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.print("<h2> This is target Servlet </h2>");
        out.print("<h2>the no of hits for this application is "
                + MyServletRequestListener.count);

    }

    public void destroy()
    {
        System.out.println("-----------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("-----------------------------------------");
    }

}

MyServletRequestListener.java
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class MyServletRequestListener implements ServletRequestListener
{

    public static int count = 0;

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent)
    {
        count++;

        System.out.println("\n###################################\n");

        System.out.println("requestInitialized method has been called in "
                + this.getClass().getName());

        ServletRequest servletRequest = servletRequestEvent.getServletRequest();

        System.out.print(servletRequest + " is Created or Initialized:");

        System.out.println("\n#####################################\n");

        /*
         * if request is created or initialized, based on that if you want to
         * perform any operation then you can do it here.
         */

    }

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent)
    {
        System.out.println("\n###################################\n");

        System.out.println("requestDestroyed method has been called in "
                + this.getClass().getName());

        ServletRequest servletRequest = servletRequestEvent.getServletRequest();

        System.out.print(servletRequest + " destroyed:");

        System.out.println("\n#####################################\n");

        /*
         * if request is destroyed , based on that if you want to perform any
         * operation then you can do it here.
         */

    }

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">
    <display-name>ServletRequestListenerDemo</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

    <servlet>
        <servlet-name>HitCountServlet</servlet-name>
        <servlet-class>HitCountServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HitCountServlet</servlet-name>
        <url-pattern>/hitCount</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>MyServletRequestListener</listener-class>
    </listener>


</web-app>

index.html
<html>
<body>
    <a href="hitCount">hitCount</a>
</body>
</html>

Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download ServletRequestListenerDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletRequestListenerDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Servlets : ServletRequestListener Introduction

    Master Core Java & Servlets!

    Subscribe to Ram N Java for beginner-friendly coding walkthroughs, request lifecycle tutorials, and hands-on Java guides!

    🔔 Subscribe to Ram N Java

    Introduction to ServletRequestListener

    In Java web applications, managing and tracking client requests is a fundamental requirement. The ServletRequestListener interface (part of the javax.servlet package) provides a callback mechanism that notifies your application when an incoming HTTP request is initialized and when it is destroyed.

    Whenever a request reaches the servlet container and comes into the scope of the web application, the container triggers an event before calling any filter or servlet. Similarly, once the response is fully generated and delivered, a completion event is dispatched. This makes ServletRequestListener the ideal choice for logging, profiling request durations, and initializing request-scoped resources.

    Key Methods in ServletRequestListener

    The interface contains two primary lifecycle methods:

    • requestInitialized(ServletRequestEvent sre): Invoked when a request comes into scope. You can access the ServletRequest instance and inspect incoming headers, parameters, remote client IP addresses, or start execution timers.
    • requestDestroyed(ServletRequestEvent sre): Invoked when the request is about to go out of scope after the response has been committed. This is suitable for calculating total execution time or releasing temporary resources.
    @WebListener
    public class RequestLoggingListener implements ServletRequestListener {

        @Override
        public void requestInitialized(ServletRequestEvent sre) {
            System.out.println("ServletRequest has been initialized: " + sre.getServletRequest().getRemoteAddr());
        }

        @Override
        public void requestDestroyed(ServletRequestEvent sre) {
            System.out.println("ServletRequest is about to be destroyed.");
        }
    }

    Why Use ServletRequestListener?

    • Centralized Request Logging: Capture metadata for every incoming HTTP request without repeating code across individual servlets.
    • Performance Telemetry: Measure total round-trip request latency across your entire web application.
    • Clean Lifecycle Separation: Keep diagnostic, monitoring, and profiling tasks cleanly decoupled from core business servlets.

    Recommended Related Tutorials

    Continue exploring servlet listeners and web architecture with these tutorials from Ram N Java:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=04DWpaXQIH4

    Click the below Image to Enlarge
    ServletRequestListener 
    ServletRequestListener 
    ServletRequestListener 
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials