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

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <listener>
        <listener-class>com.listener.HttpSessionListenerExample</listener-class>
    </listener>
</web-app>

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

 
@Override
 
public void sessionCreated(HttpSessionEvent arg) {
   
sessions++;
    System.out.println
("sessionCreated add one session into counter");
 
}

 
@Override
 
public void sessionDestroyed(HttpSessionEvent arg) {
   
sessions--;
    System.out.println
("sessionDestroyed deduct one session 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

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 *