ilovetolearn
ilovetolearn

Reputation: 2060

Using HttpSessionListener to track the total number of session in web application

My web application is build using servlets and struts. I wish to track the total number of session login to the application.

If the number of login exceeds a certain limit, I will refuse the login. How do I pass the total number of sessions from HttpSession to my struts Action class or Servlets?

Upvotes: 1

Views: 936

Answers (3)

Koitoer
Koitoer

Reputation: 19533

Dont forget to add

<listener>
<listener-class>dev.myContextListenerClass</listener-class>
</listener>

Upvotes: 0

Akkusativobjekt
Akkusativobjekt

Reputation: 2023

public class HttpSessionListener implements HttpSessionListener {

    private static final AtomicInteger sessionCount = new AtomicInteger(0);

   @Override
   public void sessionCreated(HttpSessionEvent event) {
       sessionCount.incrementAndGet();
   }

   @Override
   public void sessionDestroyed(HttpSessionEvent event) {
       sessionCount.decrementAndGet();
   }

   public static int getTotalSessionCount() {
       return sessionCount.get();
   }

}

A primitive Integer is not thread safe. With the solution above you can acess the count of open sessions with HttpSessionListener.getTotalSessionCount() . The model of the code is from this answer.

Upvotes: 2

user957654
user957654

Reputation:

you have to use the HttpSessionListener and have a static field like the following :

public class SessionCounterListener implements HttpSessionListener {

  public static int totalActiveSessions;


  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
    totalActiveSessions++;
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    totalActiveSessions--;
  }


}

and access it from anywhere like the following :

SessionCounterListener .totalActiveSessions 

please give me some feedback

Hope that helps .

Upvotes: 0

Related Questions