HttpSessionListener Example

HttpSessionListener Example explains about How to use HttpSessionListener in a web application

What is HttpSessionListener?

For knowing about HttpSessionListener, First we must understand session. Http protocol is a "stateless" protocol. The word stateless means Http protocol can't persist the information in between client and server. When a client sends a request for any resource, server receive the request and process the request and returns response.  After returning the response the server terminates the connection. When a client forwards a request for a particular resource, server consider each and every request as a separate request. In order to avoid this burden we use session. With the help of session tracking when a client request for any pages or resources container creates a session id for that particular request and return back the session id to the client along with the response object.

When I Use HttpSessionListener

Whenever a session created or destroyed, servlet container will invoke HttpSessionListener

javax.servlet.http.HttpSessionListener interface has following methods:

sessionCreated(HttpSessionEvent event)
  It will notify when the session is created.
sessionDestroyed(HttpSessionEvent event) 
  It will notify when the session gets invalidated.

Package Structure

HttpSessionListenerExample Example


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
    xmlns="" xmlns:web=""

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 getTotalActiveSession() {
return sessions;

public void sessionCreated(HttpSessionEvent arg) {
("sessionCreated add one session into counter");

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

Invoke HttpSessionListener From Servlet

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

1 2 Next

3 Responses to "HttpSessionListener Example"
  1. Sijo 2011-12-20 07:07:50.0
  1. admin 2011-12-21 07:07:50.0
  1. sijo 2011-12-22 07:07:50.0

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