JSP 实现网站在线人数统计代码
一下为程序实现网站在线人数统计代码
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;
}
}
然后配置web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.4"
xmlns="https://java.sun.com/xml/ns/j2ee"
xmlns:xsi="https://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="https://java.sun.com/xml/ns/j2ee
https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
****************************************
<!-- listeners -->
<listener>
<listener-class>
sessioncount.sessioncounter (注意此处)
</listener-class>
</listener>
*****************************************
</web-app>
建个jsp测试:
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>无标题文档</title>
<body bgcolor="#ffffff">
在线人数:<%=sessioncounter.getactivesessions()%>
</body>
</html>
以上代码可以直接使用。希望能对大家有所帮助。