實作 javax.servlet.http.HttpSessionListener 介面,監聽 Session 建立與銷毀事件,透過靜態計數器維護當前活躍 Session 數。
package com.example.listener;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionCounter implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
// 可選:記錄日誌、更新資料庫統計表
System.out.println("Session created. Active: " + activeSessions);
}
public void sessionDestroyed(HttpSessionEvent se) {
if (activeSessions > 0) activeSessions--;
System.out.println("Session destroyed. Active: " + activeSessions);
}
public static int getActiveSessions() {
return activeSessions;
}
}
<?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">
<!-- 其他配置 -->
<listener>
<listener-class>com.example.listener.SessionCounter</listener-class>
</listener>
</web-app>
注意:listener-class 必須為完整類別名稱(含套件名)。
<%@ page language="java" contentType="text/html;charset=GBK" %>
<%@ page import="com.example.listener.SessionCounter" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>線上人數統計</title>
</head>
<body bgcolor="#FFFFFF">
當前線上人數:<%= SessionCounter.getActiveSessions() %>
</body>
</html>
sessionDestroyed 在 Session 逾時或手動 invalidate() 觸發,瀏覽器關閉不會立即觸發(需等待逾時)。AtomicInteger 或 synchronized 保證原子性。HttpSessionAttributeListener 統計登入用戶數(區分遊客與會員)。@WebListener
public class SessionCounter implements HttpSessionListener {
// ... 實作同上
}
需在 web.xml 設定 metadata-complete="false" 或 Servlet 版本 ≥ 3.0。