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



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;

public void sessionCreated(HttpSessionEvent arg) {
("Inside sessionCreated one session is added to counter");

public void sessionDestroyed(HttpSessionEvent arg) {
("Inside sessionDestroyed one session is deduct from counter");

Invoke HttpSessionListener From Servlet

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


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