Servlet监听器统计在线人数

  • 首先,我们需要创建一个HttpSessionListener来监听会话的创建和销毁事件。当新的会话创建时,我们将增加在线人数;当会话销毁时,我们将减少在线人数。
public class OnlineCounterListener implements HttpSessionListener {
private static int activeSessions = 0;
@Override
public void sessionCreated(HttpSessionEvent se) {
// HttpSessionListener.super.sessionCreated(se);
activeSessions++;
System.out.println("Session created. Active sessions: " + activeSessions);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// HttpSessionListener.super.sessionDestroyed(se);
if (activeSessions > 0) {
activeSessions--;
System.out.println("Session destroyed. Active sessions: " + activeSessions);
}
}
public static int getActiveSessions(){
return activeSessions;
}
}
  • 接下来,我们需要在web.xml文件中配置该监听器,每当有新的用户访问应用程序时,都会创建一个新的会话,从而触发sessionCreated方法,增加在线人数。当会话过期或用户关闭浏览器时,会触发sessionDestroyed方法,减少在线人数。
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.example.OnlineCounterListener</listener-class>
</listener>
<!-- Servlet and JSP configurations would go here -->
</web-app>
  • 创建一个Servlet和JSP页面来显示在线人数:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/online-count")
public class OnlineCountServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int activeUsers = OnlineCounterListener.getActiveSessions();
request.setAttribute("activeUsers", activeUsers);
request.getRequestDispatcher("/online-count.jsp").forward(request, response);
}
}
  • JSP示例 (在webapp文件夹下新建online-count.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Online User Count</title>
</head>
<%
session.setMaxInactiveInterval(10);// 设置session有效时间
%>
<body>
<h1>Currently Online: ${activeUsers}</h1>
</body>
</html>

启动tomcat,浏览器访问http://localhost:8080/自定义应用程序上下文/online-count,
输出结果: Currently Online: 2

posted @   文采杰出  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示