First, write a class:
Import javax. servlet .*;
Import javax. servlet. http .*;
Public class SessionCounter implements HttpSessionListener {
Private static int activeSessions = 0;
Public void sessionCreated (HttpSessionEvent se ){
ActiveSessions ++;
}
Public void sessionDestroyed (HttpSessionEvent se ){
If (activeSessions> 0)
ActiveSessions --;
}
Public static int getActiveSessions (){
Return activeSessions;
}
}
Configure web. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
****************************************
<! -- Listeners -->
<Listener>
<Listener-class>
SessionCount. SessionCounter (note here)
</Listener-class>
</Listener>
**************************************** *
</Web-app>
Create a JSP test:
Test. jsp
<% @ Page language = "Java" contentType = "text/html; charset = GBK" %>
<% @ Page import = "java. SQL. *" %>
<% @ Page import = "SessionCount. SessionCounter" %>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
<Title> untitled document </title>
<Body bgcolor = "# FFFFFF">
Online users: <% = SessionCounter. getActiveSessions () %>
</Body>
</Html>
Test the following and you will find that the program has made statistics.