The main idea is that whenever a user accesses a Web application for the first time, it creates a session to track sessions, and can listen for changes to the current number of people online. Whenever the session is created, the number of people is +1, and when the session is destroyed, the number of people is reduced by 1 (application (ServletContext) adds a property to save the number). This allows you to create a session listener that listens for changes in the session to get the current number.
Package Com.tuxianchao.listener;
Import Javax.servlet.ServletContext;
Import javax.servlet.http.HttpSessionEvent;
Import Javax.servlet.http.HttpSessionListener; public class Onlinenumberlistener implements Httpsessionlistener {@Override public void sessioncreated (Httpsessi
OnEvent sessionevent) {System.out.println ("create session, Number plus 1");
Get ServletContext ServletContext context = Sessionevent.getsession (). Getservletcontext ();
Gets the current number Integer count = (integer) context.getattribute ("Onlinecount");
if (count = = null) {//If NULL, initialized to 1 (first accessed user) Count = new Integer (1);
else {//+1 int i = Count.intvalue ();
Count = new Integer (i + 1);
//Change the number of Context.setattribute ("Onlinecount", count); @Override public void sessiondestroyed (Httpsessionevent sessionevent) {System.out.println ("destroy session, people
Number minus 1 "); ServletContextcontext = Sessionevent.getsession (). Getservletcontext ();
Integer count = (integer) context.getattribute ("Onlinecount");
int i = Count.intvalue ();
Count = new Integer (i-1);
Context.setattribute ("Onlinecount", count);
}
}
index.jsp
<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
pageencoding=" iso-8859-1 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
After startup:
Then use chrome access: