简体   繁体   中英

Best way to count number of users in a Java EE web App

What is the best way/pattern for counting the number of active users using a particular java EE JSF web app?

The two ways I know is HttpSessionListener and using JMX web beans, if there is a third better way I am open to suggestions. I am just trying to figure out the most elegant solution.

Help is much appreciated

If you want to track the number of active users at the same time in simple Java web app built without using any frameworks , then the standard way to do that is to implement HttpSessionListener . Code below is just a reference to the way you can implement it .

import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ActiveUserCounter implements HttpSessionListener {  

      private static AtomicInteger activeSessions = new AtomicInteger();    

      public void sessionCreated(HttpSessionEvent se) {  
              activeSessions.incrementAndGet();  
      }  

      public void sessionDestroyed(HttpSessionEvent se) {  
                if(activeSessions.get() > 0)  
                       activeSessions.decrementAndGet();  
      }  

     public static int getActiveSessions() {  
             return activeSessions.get();  
      }   
}  

Define the listener class in your web.xml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM