Servlet Listener Example

Servlet Listener Example explains step by step details of implementing a Servlet Listener

Servlet Listener is helpful for listening various events inside a servlet container, such as add an attribute in a session, create a session, to manipulate these events you need to configure listener class in web.xml

Please see the following Java Servlet Listener Example

HttpSessionAttributeListener Example
HttpSessionBindingListener Example
HttpSessionListener Example
ServletContextAttributeListener Example
ServletContextListener Example

Package Structure

Servlet Listener Example

For example HttpSessionListener, we need to configure web.xml in the following way

web.xml

<listener>
  <listener-class>com.listener.HttpSessionListenerExample</listener-class>
</listener>

HttpSessionListenerExample.java

package com.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class HttpSessionListenerExample implements HttpSessionListener {

 
private static int sessions;

 
public static int getTotalNoOfActiveSession() {
   
return sessions;
 
}

 
@Override
 
public void sessionCreated(HttpSessionEvent arg) {
   
sessions++;
    System.out.println
("Inside sessionCreated one session is added to counter");
 
}

 
@Override
 
public void sessionDestroyed(HttpSessionEvent arg) {
   
sessions--;
    System.out.println
("Inside sessionDestroyed one session is deduct from counter");
 
}
}

Invoke HttpSessionListener From Servlet

HttpSession session = request.getSession(); //sessionCreated() method is invoked
session.setAttribute("url", "www.javatips.net"); 
session.invalidate();  //sessionDestroyed() method is invoked

 









Your email address will not be published. Required fields are marked *