Saturday, 6 September 2014

Add ServletRequestListener using Deployment Descriptor

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class RequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("Request Destroyed");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
       System.out.println("Request initialized");
       
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
    <listener>
        <description>RequestListener</description>
        <listener-class>RequestListener</listener-class>
    </listener>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.*;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        try(PrintWriter out = res.getWriter()){
            ServletContext context = req.getServletContext();
            System.out.println("In doGet method");
        }
    }
}

Run ' SampleApp', server console has messages like below.

Info:   Request initialized
Info:   In doGet method
Info:   Request Destroyed





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment