萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 實現線上人數統計:HttpSessionListener 完整實作

核心原理

實作 javax.servlet.http.HttpSessionListener 介面,監聽 Session 建立與銷毀事件,透過靜態計數器維護當前活躍 Session 數。

完整實作代碼

1. SessionCounter 監聽器類別

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;
    }
}

2. 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">

    <!-- 其他配置 -->

    <listener>
        <listener-class>com.example.listener.SessionCounter</listener-class>
    </listener>

</web-app>

注意:listener-class 必須為完整類別名稱(含套件名)。

3. JSP 顯示線上人數

<%@ 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>

進階優化與注意事項

  1. 集群環境:單機靜態變數無法共享,需改用資料庫、Redis 或 Session 複製機制。
  2. 準確性:sessionDestroyed 在 Session 逾時或手動 invalidate() 觸發,瀏覽器關閉不會立即觸發(需等待逾時)。
  3. 效能:靜態計數器讀寫極快,高併發下建議使用 AtomicInteger 或 synchronized 保證原子性。
  4. 擴展:可結合 HttpSessionAttributeListener 統計登入用戶數(區分遊客與會員)。

Servlet 3.0+ 註解式註冊 (無需 web.xml)

@WebListener
public class SessionCounter implements HttpSessionListener {
    // ... 實作同上
}

需在 web.xml 設定 metadata-complete="false" 或 Servlet 版本 ≥ 3.0。

copyright © 萬盛學電腦網 all rights reserved