Friday 15 August 2014

Add Listeners Programmatically

ServletContext interface provides below methods to add listeners to the Servlet context.
    addListener(Class<? extends EventListener> listenerClass)
    addListener(String className)
    addListener(T t)

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;


public class ReqAttrListener implements ServletRequestAttributeListener {

    @Override
    public void attributeAdded(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Added");
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Removed");
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Replaced");
  }
}

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 ReqAttrListener");
        context.addListener(ReqAttrListener.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.*;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        try(PrintWriter out = res.getWriter()){
           req.setAttribute("name", "Krishna");
           req.setAttribute("name", "Arjun");
           req.removeAttribute("name");
        }
    }
}

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

Info:   Adding ReqAttrListener
Info:   ContextListener1 Initialized
Info:   Loading application [servlet] at [/servlet]
Info:   servlet was successfully deployed in 322 milliseconds.
Info:   name Added
Info:   name Replaced
Info:   name Removed





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment