Sunday, 12 October 2014

Servlet Listener

ServletListener is a small program which will listen to some events. Events can be anything like session event, context event, context attribute event, request event.
In this chapter I will explain-
  1. ServletContextListener
  2. ServletContextAttributeListener
  3. HttpSessionListener
  4. HttpSessionAttributeListener
  5. ServletRequestListener
ServletContextListener-
I explained the ServletContext in previous chapter. So, I am assuming you know about ServletContext.
ServletContext is a object that consist config to Share among Servlets.

Now assume you want execute some piece of code, when ever application context initialize or destroyed. In this scenario you need to know some events when context is initialize or destroyed.
Don't worry!!! javax.servlet.ServletContextListener interface provide this.

Below is the methods description of SessionContextListener-

 void contextDestroyed(ServletContextEvent sce)
          Receives notification that the ServletContext is about to be shut down.
 void contextInitialized(ServletContextEvent sce)
          Receives notification that the web application initialization process is starting.

For example I want to load the property file when I start the server.

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        try {
          String fileName = ctx.getInitParameter("configFile");
          System.out.println(fileName);
          File file = new File(fileName);
          FileInputStream fis = new FileInputStream(file);
  
          Properties p = new Properties();

          p.load(fis);
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        System.out.println("Context destroyed");
       
    }
     
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyContextListener</listener-class>
</listener>

Now Property is ready to use.Whenever context will initialize Property will be loaded.

ServletContextAttributeListener
This interface and extends the java.util.EventListener class.Whenever attribute of SessionContext added/changed/removed this listener receive the notification event. But to get the notification, your servlet context attribute listener class should be register in the web container i.e. web.xml.

Below is the method description of this listener-
void attributeAdded(ServletContextAttributeEvent event)
          Receives notification that an attribute has been added to the ServletContext.
 void attributeRemoved(ServletContextAttributeEvent event)
          Receives notification that an attribute has been removed from the ServletContext.
 void attributeReplaced(ServletContextAttributeEvent event)
           

For Example-

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextAttributeListener implements ServletContextAttributeListener {
     
    public void attributeAdded(ServletContextAttributeEvent scab){      
            System.out.println("attribute Added");
    }

    public void attributeRemoved(ServletContextAttributeEvent scab) {
       System.out.println("attribute Removed"); 
    }

    public void attributeReplaced(ServletContextAttributeEvent scab) {       
       System.out.println("attribute Replaced");       
    }
     
}


Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyContextAttributeListener</listener-class>
</listener>

MyServlet.java-

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
     PrintWriter out = response.getWriter();
     ServletContext sc = getServletContext();
     sc.setAttribute("name", "XXX");
     sc.setAttribute("age", "23");
     sc.removeAttribute("name");
}    

you can verify the output log and you will get to know that when setting the attribute in ServletContext then attributeAdded() is getting invoked and when removeAttribute() is called then attributeRemoved() method is getting invoked by container.

HttpSessionListener
Whenever changes to the list of active sessions happen in a web application. i.e. new session is created or destroyed then this listener is notified.

Below is the method descriptor of this listener-
void sessionCreated(HttpSessionEvent se)
          Notification that a session was created.
 void sessionDestroyed(HttpSessionEvent se)
          Notification that a session is about to be invalidated.

For example suppose we want count the active session-

MyHttpSessionListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener{
  private int activeSession=0;  
   
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
 activeSession++;
 System.out.println("sessionCreated");
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
 activeSession--;
 System.out.println("sessionDestroyed");
  } 
     
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyHttpSessionListener</listener-class>
</listener>

 MyServlet.java-


public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    

  HttpSession session = request.getSession(); //sessionCreated() will be execute
  //do something with session 
  session.invalidate();  //sessionDestroyed() will be execute
}    


HttpSessionAttributeListener
Whenever attibute added/deleted/replaced to the session object this listener will be notified by web container.

Below is the method descriptor of this listener
void attributeAdded(HttpSessionBindingEvent se)
          Notification that an attribute has been added to a session.
 void attributeRemoved(HttpSessionBindingEvent se)
          Notification that an attribute has been removed from a session.
 void attributeReplaced(HttpSessionBindingEvent se)
          Notification that an attribute has been replaced in a session.

MyHttpSessionAttributeListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener{

   
     @Override
     public void attributeAdded(HttpSessionBindingEvent event) { 
      String attributeName = event.getName(); 
      Object attributeValue = event.getValue(); 
      System.out.println(attributeName + " : " + attributeValue);
     }
 
     @Override
     public void attributeRemoved(HttpSessionBindingEvent event) {
 String attributeName = event.getName(); 
        Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue);
    }
 
     @Override
     public void attributeReplaced(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
 Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue); 
     }
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyHttpSessionAttributeListener </listener-class>
</listener>

 MyServlet.java-


public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    

  HttpSession session = request.getSession(); 
  session.setAttribute("name", "xxx"); //attributeAdded() will be execute
  session.setAttribute("name", "yyy"); //attributeReplaced() will be execute
  session.removeAttribute("name"); //attributeRemoved() will be execute
  session.invalidate(); 
}    

ServletRequestListener 
Whenever request coming into the the web container or request going out from the web container then this listener is notified.

Below is the method description of this listener
void requestDestroyed(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to go out of scope of the web application.
 void requestInitialized(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to come into scope of the web application.

1 comment:

  1. Java Class By Rk: Servlet Listener >>>>> Download Now

    >>>>> Download Full

    Java Class By Rk: Servlet Listener >>>>> Download LINK

    >>>>> Download Now

    Java Class By Rk: Servlet Listener >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete