`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>
宣告的 `Integer number` 從未賦值,顯示時應用 `application.getAttribute("visitorCount")`。
<%@ 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分鐘無活動移除
%>