By Sessionlistenr can listen to the creation and destruction of the session, so first write a class Mysessionlistener, Implement the Javax.servlet.http.HttpSessionListener interface and its sessioncreated (), Sessiondestroyed () methods:
Import Java.util.HashSet;
Import Javax.servlet.ServletContext;
Import javax.servlet.http.HttpSession;
Import javax.servlet.http.HttpSessionEvent;
Import Javax.servlet.http.HttpSessionListener;
public class Mysessionlistener implements Httpsessionlistener {
public void sessioncreated (Httpsessionevent event) {
HttpSession session = Event.getsession ();
ServletContext application = Session.getservletcontext ();
Save all sessions in application range by a hashset set
HashSet sessions = (hashset) application.getattribute ("Sessions");
if (sessions = = null) {
Sessions = new HashSet ();
Application.setattribute ("Sessions", sessions);
}
Newly created sessions are added to the hashset set
Sessions.add (session);
You can remove the sessions collection from the application range elsewhere
Then use Sessions.size () to get the current active session number, which is "online number"
}
public void sessiondestroyed (Httpsessionevent event) {
HttpSession session = Event.getsession ();
ServletContext application = Session.getservletcontext ();
HashSet sessions = (hashset) application.getattribute ("Sessions");
Destroyed sessions are removed from the HashSet set
Sessions.remove (session);
}
}
Then configure the Sessionlistener and session timeout (10 minutes) separately in Web.xml:
<listener>
<listener-class> Full path mysessionlistener</listener-class>
</listener>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
Finally in the JSP page code using the following code to achieve the current number of online statistics output:
.......
Current online:
<%
HashSet sessions= (HashSet) Application.getattribute ("Sessions");
Out.print (Sessions.size ());
%>
.......