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;
}
}
then 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>
build 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: <%=sessioncounter.getactivesessions ()%>
</body>
</html>
The following test, you will find that the program has already counted the results.