Saturday 6 September 2014

Add ServletRequestListener using addListener method

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");
       
    }
}

import javax.servlet.*;
import javax.servlet.annotation.WebListener;

@WebListener
public class ContextListener1 implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        
        /* Add Context Listener */
        System.out.println("Adding ServletRequestListener");
        context.addListener(RequestListener.class);
     
        System.out.println("ContextListener1 Initialized");
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Context Listener1 Destroyed");
    }
}

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:   Adding ServletRequestListener
Info:   ContextListener1 Initialized
Info:   Loading application [servlet] at [/servlet]
Info:   servlet was successfully deployed in 256 milliseconds.
Info:   Request initialized
Info:   In doGet method
Info:   Request Destroyed




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment