萬盛學電腦網

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

JSP 利用 Application 統計線上人數實作

核心原理

`ServletContext` (JSP 隱式物件 `application`) 代表整個 Web 應用,生命週期 = 應用部署到卸載。所有用戶共享同一個 `application` 物件,適合儲存全域計數器。

完整實作代碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head><title>線上人數統計</title></head>
<body>

<%!
    // 宣告為類別成員變數 (所有請求共享同一 Servlet 實例的此欄位)
    // 注意:這裡的 number 其實沒有被正確使用,見下方分析
    Integer number; 
    
    // synchronized 確保執行緒安全
    synchronized void incrementVisitor() {
        ServletContext application = getServletContext();
        Integer count = (Integer) application.getAttribute("visitorCount");
        
        if (count == null) {
            count = 1;
        } else {
            count = count + 1;
        }
        application.setAttribute("visitorCount", count);
    }
%>

<%
    // 每個新 Session 代表一位新訪客 (簡易統計邏輯)
    if (session.isNew()) {
        incrementVisitor();
    }
    
    // 取得最新計數顯示
    Integer currentCount = (Integer) application.getAttribute("visitorCount");
%>

<p><font size="2" color="blue">簡易頁面訪問計數器</font></p>
<p><font size="2" color="#000000">
    歡迎訪問,您是第 <%= currentCount != null ? currentCount : 0 %> 位訪客
</font></p>

</body>
</html>

代碼問題分析與修正

問題 1:number 成員變數未被使用

宣告的 `Integer number` 從未賦值,顯示時應用 `application.getAttribute("visitorCount")`。

問題 2:統計邏輯 — 「新 Session = 新訪客」不準確

  • 同一用戶關閉瀏覽器重開 → 新 Session → 重複計數
  • 爬蟲/機器人產生 Sesion → 虛高統計
  • Session 逾時前重訪不計數 (isNew()=false)

改進版:IP 基礎去重 + 原子操作

<%@ page import="java.util.concurrent.atomic.AtomicInteger" %>
<%@ page import="javax.servlet.ServletContext" %>
<%
    ServletContext app = getServletContext();
    String clientIp = request.getRemoteAddr();
    String ipAttr = "visitor_ips"; // 儲存已計數 IP 集合 (簡易版用逗號分隔字串,生產環境用 Redis/Set)
    
    // 簡易版:Application 存 IP 字串,實際建議用 ConcurrentHashMap 或 Redis
    String ips = (String) app.getAttribute(ipAttr);
    boolean isNewVisitor = false;
    
    if (ips == null || !ips.contains(clientIp)) {
        isNewVisitor = true;
        // 線程安全更新 IP 列表 (簡易同步)
        synchronized (app) {
            ips = (String) app.getAttribute(ipAttr); // Double-check
            if (ips == null || !ips.contains(clientIp)) {
                ips = (ips == null ? "" : ips + ",") + clientIp;
                app.setAttribute(ipAttr, ips);
            }
        }
    }
    
    // 使用 AtomicInteger 保證計數器原子性
    AtomicInteger counter = (AtomicInteger) app.getAttribute("visitorCount");
    if (counter == null) {
        counter = new AtomicInteger(0);
        AtomicInteger existing = (AtomicInteger) app.getAttribute("visitorCount");
        if (existing != null) counter = existing; // 另一執行緒已建立
        else app.setAttribute("visitorCount", counter);
    }
    
    if (isNewVisitor) counter.incrementAndGet();
%>
<p>總訪客數: <%= counter.get() %> (IP 去重)</p>

生產環境最佳實踐

層面簡易版 (Application)進階版 (Redis)
儲存結構Application 屬性 (Map)Redis: INCR counter, SET ip:set
叢集支援❌ 單機✅ 多節點共享
持久化❌ 重啟歸零✅ AOF/RDB
IP 去重字串搜尋 O(n)SET SISMEMBER O(1)
效能同步鎖爭用無鎖原子操作

應用擴展:即時線上用戶列表

<%-- 登入時 --%>
<% 
    String user = (String) session.getAttribute("username");
    if (user != null) {
        Map online = (Map) application.getAttribute("onlineUsers");
        if (online == null) online = new ConcurrentHashMap<>();
        online.put(session.getId(), System.currentTimeMillis()); // 值存最後活動時間
        application.setAttribute("onlineUsers", online);
    }
%>

<%-- 定時清理 (ServletContextListener 或 Quartz) --%>
<%
    Map online = (Map) application.getAttribute("onlineUsers");
    long now = System.currentTimeMillis();
    online.entrySet().removeIf(e -> now - e.getValue() > 30 * 60 * 1000); // 30分鐘無活動移除
%>

總結

  • `application` 適合單機、非關鍵、簡易統計
  • 計數器務必執行緒安全 (synchronized / AtomicInteger / ConcurrentHashMap)
  • 生產環境統計請用 Redis / 資料庫 / 專業分析工具 (GA, Matomo)
  • 區分「頁面瀏覽量 (PV)」、「獨立訪客 (UV)」、「線上人數」三種指標
copyright © 萬盛學電腦網 all rights reserved