15 - Servlet Listeners: Page 4 of 4

15.2.5 ServletRequestListener

ServletRequestListener listens to ServletRequestEvent event which gives a notification when request is created or destroyed. ServletRequestListener  is the interface and it defines two methods –

  • void requestDestroyed(ServletRequestEvent e) – This method is executed when request is destroyed
  • void requestInitialized(ServletRequestEvent e)- This method is executed when request  is initialized.

Request object can be Obtained from  HttpRequestEvent.

Let s write a sample listener which will print some message describing the event.

  1. Add listener entry in web.xml
<listener>
 <description> Servlet Request Listener Example</description>
 <listener-class>com.servlet.tutorial.MyServletRequestListener</listener-class>
</listener>

  1. Write MyServletRequestListener code
package com.servlet.tutorial;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyServletRequestListener  implements ServletRequestListener {
    /**
     * Default constructor. 
     */
    public MyServletRequestListener() {
    }
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) 
    {
        ServletRequest request = servletRequestEvent.getServletRequest();
        System.out.println("Request Destroyed");
    }
    public void requestInitialized(ServletRequestEvent servletRequestEvent) 
    {
        ServletRequest request = servletRequestEvent.getServletRequest();
        System.out.println("Request initialized");
    }
}

Testing

Hit any of the url we have used because each hit to a server will be a new request.

Lets try http://localhost:8080/HelloWorld/MyServlet

15.2.6 ServletRequestAttributeListener

ServletRequestAttributeListener listens to ServletRequestAttributeEvent  event which gives a notification when any  object is added, removed or replaced from request .

ServletRequestAttributeListener is the interface and it defines three methods –

  • attributeAdded(ServletRequestAttributeEvent  e): It notifies whenever a new  attribute is added to the request.
  • attributeRemoved(ServletRequestAttributeEvent  e): It notifies whenever the attribute is removed from the request.
  • attributeReplaced(ServletRequestAttributeEvent  e): It notifies whenever the attribute gets replaced on the request.

Attribute name and value  that has been added, removed or replaced  can be obtained from the getName() and getValue() method of ServletRequestAttributeEvent 
Let s write a sample listener which will print some message describing the event and attribute values

  1. Add listener entry in web.xml
<listener>
 <description>Servlet Request Attribute Listener Example</description>
 <listener-class>com.servlet.tutorial.MyServletRequestAttributeListener</listener-class>
</listener>

  1. Write MyServletRequestAttributeListener Code
package com.servlet.tutorial;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;
public class MyServletRequestAttributeListener  implements ServletRequestAttributeListener {
    /**
     * Default constructor. 
     */
    public MyServletRequestAttributeListener() {
    }
    public void attributeAdded(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("Attribute has been added");
        String attributeName = servletRequestAttributeEvent.getName();
        Object attributeValue = servletRequestAttributeEvent.getValue();
        System.out.println("Attribute Name ::" + attributeName);
        System.out.println("Attribute Value ::" + attributeValue.toString());
    }
    public void attributeRemoved(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("Attribute has been added");
        String attributeName = servletRequestAttributeEvent.getName();
        Object attributeValue = servletRequestAttributeEvent.getValue();
        System.out.println("Attribute Name ::" + attributeName);
        System.out.println("Attribute Value ::" + attributeValue.toString());
    }
    public void attributeReplaced(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("Attribute has been added");
        String attributeName = servletRequestAttributeEvent.getName();
        Object attributeValue = servletRequestAttributeEvent.getValue();
        System.out.println("Attribute Name ::" + attributeName);
        System.out.println("Attribute Value ::" + attributeValue.toString());
    }
}

  1. Add servlet entry in web.xml
 <servlet>
    <servlet-name>ServletRequestAttributeListenerDemo</servlet-name>
    <servlet-class>com.servlet.tutorial.ServletRequestAttributeListenerDemo </servlet-class>
 </servlet>
  <servlet-mapping>
    <servlet-name>ServletRequestAttributeListenerDemo</servlet-name>
    <url-pattern>/ServletRequestAttributeListenerDemo</url-pattern>
 </servlet-mapping>

  1. Write ServletRequestAttributeListenerDemo servlet code
package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletRequestAttributeListenerDemo extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        String attributeName="RequestAttribute";
        String attributeValue="Initial Value";
        request.setAttribute(attributeName, attributeValue);
        attributeValue="New Value";
        request.setAttribute(attributeName, attributeValue);
        request.removeAttribute(attributeName);
    }
}

Testing

Hit http://localhost:8080/HelloWorld/ServletRequestAttributeListenerDemo

Note- getValue() returns the  previous value in case of replace because listener is executed before it is actually replaced.

  1. HttpSessionActivationListener

HttpSessionActivationListener listens to a session when sssions object migrates from one virtual machine  to another. HttpSessionActivationListener only has any relevance when a session is part of a web application in a distributed environment. So we will not be able to have a example here.

Note: This listener notifies the objects itself about the below events.

HttpSessionActivationListener  listens to HttpSessionEvent  and HttpSessionActivationListener   interface has two methods

·         sessionDidActivate(HttpSessionEvent e) – this method is executed when session has activated.
·         sessionWillPassivate(HttpSessionEvent e- this method will execute when session is about to passivate.
  1. HttpSessionBindingListener

This listener is used when object themselves want to know that they have been added to session or removed from session.

You might be confused about the difference between HttpSessionBindingListener and HttpSessionAttributeListener.  HttpSessionAttributeListener class just listens if any object is added, removed or replaced to session but HttpSessionBindingListener notifies the object of classes which are getting added or removed from session.

Note :Since this listener notifies the object , object classes has to implement this interface and there is no need of any listener entry for this listener in web.xml

HttpSessionBindingListener listens to HttpSessionBindingEvent and defines following methods

  • valueBound(HttpSessionBindingEvent e) – notifies object when object is added to session
  • valueUnbound(HttpSessionBindingEvent e) – notifies when object is removed from session.

Let s write a sample listener which will print some message describing the event and attribute values

  1. Define a bean class Person which will implement HttpSessionBindingListener
package com.servlet.tutorial;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class Person implements HttpSessionBindingListener{
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("I am added to session !!");
    }
    @Override
    public void valueUnbound(HttpSessionBindingEvent HttpSessionBindingEvent) {
        System.out.println("I am removed  to session !!");
    }
}

  1. Define a HttpSessionBindingListenerDemo servlet entry in web.xml
<servlet>
    <servlet-name>HttpSessionBindingListenerDemo</servlet-name>
    <servlet-class>com.servlet.tutorial.HttpSessionBindingListenerDemo </servlet-class>
 </servlet>
  <servlet-mapping>
    <servlet-name>HttpSessionBindingListenerDemo</servlet-name>
    <url-pattern>/HttpSessionBindingListenerDemo</url-pattern>
 </servlet-mapping>
  
  1. Write a HttpSessionBindingListenerDemo servlet which will add Person object in session and remove it from session
package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class HttpSessionBindingListenerDemo extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
            {
            Person p = new Person();
            HttpSession session = request.getSession();
            session.setAttribute("person",p);
            session.removeAttribute("person");
    }
}

Testing

Hit http://localhost:8080/HelloWorld/HttpSessionBindingListenerDemo

Like us on Facebook