若需在伺服器端即時掌握用戶 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 關鍵字確保多執行緒環境下計數器準確${sessionScope.onlineCount}ServletContext.log() 寫入伺服器日誌,便於事後稽核
<web-app>
<listener>
<listener-class>com.example.listener.OnlineCounterListener</listener-class>
</listener>
<!-- 放在其他 listener 之後即可 -->
</web-app>
原詢問提到「將用戶正在瀏覽的 URL 發送到伺服器」。單純 Session 監聽器無法做到,需結合:
request.getRequestURI() 到 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);
}
}
WEB-INF/classesweb.xml 加入 listener 宣告掌握 HttpSessionListener,即可建立即時線上人數統計、Session 存活監控、用戶行為分析等核心功能。