核心類別:SessionCounter
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 測試頁面
<%@ page language="Java" contentType="text/html;charset=GBK"%>
<%@ page import="SessionCount.SessionCounter" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>線上人數測試</title>
</head>
<body bgcolor="#FFFFFF">
線上人數: <%= SessionCounter.getActiveSessions() %>
</body>
</html>
運作原理
- 容器啟動時實例化
SessionCounter,靜態變數 activeSessions 初始為 0。
- 用戶首次訪問建立 Session 觸發
sessionCreated,計數器 +1。
- Session 逾時或手動
invalidate() 觸發 sessionDestroyed,計數器 -1。
- 任意頁面呼叫靜態方法
getActiveSessions() 即可取得當前線上人數。
注意事項與擴充
- 叢集環境:單機靜態變數無法共享,需改用資料庫、Redis 或 Session 複製機制。
- 準確性:瀏覽器關閉不會立即觸發
sessionDestroyed,需等待逾時 (預設 30 分鐘),統計為「近期活躍」而非「即時在線」。
- 效能:靜態計數器極輕量,高併發下建議使用
AtomicInteger 避免競態條件。