Thursday, 9 October 2014

Call a method just before a session expires

In this tutorial we gonna learn that how to call a specific method when a session is going to be destroyed or invalidated by the application container. First of all we need to know why we are doing this. Well it may have many applications but typically we use it for updating user counts, releasing resources etc. We could use HttpSessionListener and do the job in sessionDestroyed() method.

How to implement HttpSessionListener ?

To implement SessionListner we just have to make a class that implements HttpSessionListener and override the sessionDestroyed() method. If you want to call a method when a session is created then you can override sessionCreated() method. After overriding these methods you can do whatever you want to do. You can even get the data associated with that session in these methods.

Example :

package service;
import java.util.logging.Logger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListner implements HttpSessionListener {
   static final Logger log = Logger.getAnonymousLogger();
   private static int totalActiveSessions;
   public static int getTotalActiveSession(){
  return totalActiveSessions;
   public void sessionCreated(HttpSessionEvent se) {
   public void sessionDestroyed(HttpSessionEvent se) {
                // se.getAttribute("username") if you want to get session data 

Now after making this class you have to register this listener to your web.xml file. To do this just add below line of code.


Now whenever any session will be invalidated or timed out, the sessionDestroyed method will be called.


  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog.
    It is very nicely explained. Your article adds best knowledge to our Java Online Training from India.
    or learn thru Java Online Training from India Students.

  2. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb.
    This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolites festivity to pity. I appreciated what you ok extremely here 

    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

  3. Thanks for the information.Get the best Selenium Course in Chennai from Hope Tutors at Affordable Fees.

  4. Great post and informative was awesome to read, thanks for sharing this great content to my vision.
    Good discussion.
    Java Training in Chennai
    Java Training in Coimbatore
    Java Training in Bangalore