Home>

1. Create a listener sessionlistener in the project and implement the httpsessionlistener interface, the code is 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 creation:" + 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 listener</description>
 <listener-class>com.xxx.sessionlistener</listener-class>
</listener>

3. Show the number of people online in the jsp page

<%
 int count=com.xxx.sessionlistener.getcount ();
 out.println ("Number of users:" + count);
%>

Note:There are many interfaces for session monitoring in servlets.The function is very flexible,The most commonly used are listening sessions and attributes. To clarify the concept here,The meaning of session listening and attribute listening in servlet is different.Session monitoring does not refer to placing or destroying a session as we generally understand. This is the function of attribute monitoring.Because the syntax for placing sessions in a servlet is session.setattribute ("session name", the object to put). The session listener listens to the http connection. As long as there is a user connected to the server, even if the connection is a blank jsp page, the session event will be triggered, so the session here actually refers to the connection, which is used to count the current online The number of users is most suitable.

  • Previous Million levels know PHP development for user data capture and analysis
  • Next Practical bank transfer stored procedures and serial number generation stored procedures