首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Servlet 監聽器實戰:實作 HttpSessionListener 追蹤線上用戶數

     編輯:Java 相關知識

若需在伺服器端即時掌握用戶 Session 建立與銷毀事件(如統計線上人數、追蹤用戶活動),HttpSessionListener 是標準解決方案。本文提供完整實作範例與部署說明。

核心介面與生命週期方法


package com.example.listener;

import javax.servlet.*;
import javax.servlet.http.*;

public final class OnlineCounterListener implements HttpSessionListener {
    private int activeSessions = 0;
    private ServletContext context = null;

    @Override
    public synchronized void sessionCreated(HttpSessionEvent se) {
        activeSessions++;
        HttpSession session = se.getSession();
        session.setAttribute("onlineCount", activeSessions);
        log("Session 建立: " + session.getId() + " | 當前線上: " + activeSessions);
    }

    @Override
    public synchronized void sessionDestroyed(HttpSessionEvent se) {
        activeSessions--;
        HttpSession session = se.getSession();
        session.setAttribute("onlineCount", activeSessions);
        log("Session 銷毀: " + se.getSession().getId() + " | 當前線上: " + activeSessions);
    }

    public int getCount() { return activeSessions; }

    private void log(String msg) {
        if (context != null) context.log("OnlineCounterListener: " + msg);
        else System.out.println("OnlineCounterListener: " + msg);
    }
    
    // ServletContextListener 可注入 context(略)
}

關鍵設計細節

  • 同步化:synchronized 關鍵字確保多執行緒環境下計數器準確
  • 屬性同步:將計數存入 Session 供 JSP/頁面直接讀取:${sessionScope.onlineCount}
  • 日誌記錄:透過 ServletContext.log() 寫入伺服器日誌,便於事後稽核

web.xml 部署設定


<web-app>
    <listener>
        <listener-class>com.example.listener.OnlineCounterListener</listener-class>
    </listener>
    <!-- 放在其他 listener 之後即可 -->
</web-app>

容器相容性注意

  • Tomcat 4.0+ 完整支援
  • Tomcat 3.1 不支援 Servlet 2.3 監聽器 API
  • 其他容器請參閱各自文件確認 Servlet 版本支援

進階應用:追蹤用戶瀏覽軌跡

原詢問提到「將用戶正在瀏覽的 URL 發送到伺服器」。單純 Session 監聽器無法做到,需結合:

  1. Filter 攔截每個請求,記錄 request.getRequestURI() 到 Session
  2. Ajax 輪詢 或 WebSocket 即時推送至伺服器
  3. SessionAttributeListener 監聽 Session 屬性變更

// 簡易請求追蹤 Filter
@WebFilter("/*")
public class RequestTrackingFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("lastVisitedUrl", request.getRequestURI());
            session.setAttribute("lastVisitTime", System.currentTimeMillis());
        }
        chain.doFilter(req, res);
    }
}

部署驗證

  1. 編譯類別至 WEB-INF/classes
  2. 修改 web.xml 加入 listener 宣告
  3. 重新啟動 Web 應用
  4. 瀏覽器開啟多個分頁/視窗測試,觀察計數變化
  5. 檢查伺服器日誌確認事件記錄

掌握 HttpSessionListener,即可建立即時線上人數統計、Session 存活監控、用戶行為分析等核心功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved