JSP 內置 session 對象代表用戶會話,支援屬性存取與生命周期管理。本文展示如何遍歷 Session 所有屬性名稱與值,並補充 Session 常用 API、作用域邊界、集群環境注意事項,助力會話管理功能開發。
遍歷 Session 所有屬性代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*" %>
<html><body>
<%
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String key = names.nextElement();
Object val = session.getAttribute(key);
out.print(key + " = " + val + "<br>");
}
%>
</body></html>
Session 核心 API 速查
| 方法 | 說明 |
setAttribute(String name, Object value) | 存入屬性,覆蓋同名舊值 |
getAttribute(String name) | 取得屬性,不存在返回 null |
removeAttribute(String name) | 移除屬性 |
getAttributeNames() | 返回所有屬性名 Enumeration |
getId() | 獲取會話唯一標識 JSESSIONID |
getCreationTime() | 會話創建時間毫秒數 |
getLastAccessedTime() | 最後訪問時間 |
getMaxInactiveInterval() / setMaxInactiveInterval(int seconds) | 獲取/設置超時時間(秒),負數為永不過期 |
invalidate() | 銷毀會話,移除所有屬性 |
isNew() | 客戶端是否尚未加入會話(無 Cookie/URL 重寫) |
Session 生命周期與作用域
- 創建:首次調用
request.getSession() 或 request.getSession(true),或 JSP 頁面 <%@ page session="true" %> (預設)
- 存活:持續訪問間隔
< maxInactiveInterval,每次訪問刷新 lastAccessedTime
- 銷毀:超時自動銷毀、調用
invalidate()、伺服器關閉/重啟
- 作用域:同一瀏覽器進程 (共享 Cookie) 內的所有請求;新開瀏覽器/無痕模式 = 新會話
web.xml 統一配置超時
<session-config>
<session-timeout>30</session-timeout> <!-- 分鐘 -->
</session-config>
集群/分布式環境注意事項
- Session 複製:Tomcat 配置
<Cluster> 或使用 Redis/Memcached 外部化存儲 (Spring Session)
- 黏性會話:負載均衡器按 JSESSIONID 路由至固定節點,避免 Session 不一致
- 序列化要求:存入 Session 的對象必須實現
Serializable,以支持跨節點複製/持久化
安全最佳實踐
- 敏感數據 (權限、金額) 勿直接存 Session,存用戶 ID 後查權限表
- 登入時重新生成 Session ID (
request.changeSessionId() Servlet 3.1+),防會話固定攻擊
- HTTPS 全站傳輸,Cookie 設置
Secure; HttpOnly; SameSite=Strict
- 定期清理失效 Session,防內存洩漏
常見誤區
- 以為
session.setAttribute 即時寫入硬盤 — 內存中,僅序列化/持久化時寫盤
- 不同瀏覽器標籤頁共享 Session — 同進程共享 Cookie,不同進程/無痕模式隔離
session="false" 頁面無法使用 session 對象 — 會拋出編譯錯誤
掌握 Session 遍歷與管理,是實現用戶狀態感知、購物車、權限控制等核心業務的基礎。
- 上一篇文章: 從零搭建 JSP 開發環境並實現留言簿:JDK、Tomcat、MySQL、JDBC 全流程指南
- 下一篇文章: 深度理解 Struts 1 核心機制:FormBean 自動填充、Action 生命周期與標籤綁定原理
Copyright ©
程式碼之家 All Rights Reserved