Online population statistics using Java listeners

  • 2020-04-01 04:12:57
  • OfStack

This article example for you to share the Java listener to achieve online statistics of the number of specific code, for your reference, the specific content is as follows

1. Create the listener class SessionListener in the project and implement the HttpSessionListener interface as follows


import javax.servlet.http.HttpSessionEvent;
 
import javax.servlet.http.HttpSessionListener;
 
public class SessionListener implements HttpSessionListener {
 private static int count = 0;
 
 public void sessionCreated(HttpSessionEvent se) {
 count++;
 System.out.println("session Create: " + new java.util.Date());
 }
 
 public void sessionDestroyed(HttpSessionEvent se) {
 count--;
 System.out.println("session Destruction: " + new java.util.Date());
 }
 
 public static int getCount() {
 return count;
 }
}

2. Configure web. XML


<listener>
 <description>session The listener </description> 
 <listener-class>com.xxx.SessionListener</listener-class>
</listener>

3. The online number is displayed in the JSP page


<%
 int count=com.xxx.SessionListener.getCount();
 out.println(" Online number: "+count);
%>

Note: there are many interfaces for session monitoring in servlets with flexible functions. The most common ones are session monitoring and Attribute monitoring. To clarify the concept, there is a difference between the meaning of session monitoring in servlets and that of Attribute monitoring. The meaning of session monitoring is not to place a session or destroy a session as we generally understand it. This is the function of Attribute monitoring, because the syntax for placing sessions in servlets is session.setattribute (" session name ", the object to be put into). However, session monitoring is an HTTP connection. As long as there is a connection between the user and the server, even if the connection is a blank JSP page, the session event will also be triggered.

This kind of online population statistics method is not very special, I hope this article for everyone's learning help, some inspiration.


Related articles: