HTTP 協議無狀態特性導致無法在請求間保持用戶狀態。JSP 通過 HttpSession 實現會話管理,其底層基於 Cookie 或 URL 重寫:
<session-timeout>)Integer、String),不能存基本類型(int、double)| 方法 | 說明 |
|---|---|
getId() | 獲取唯一會話標識,用於日誌追蹤或分佈式會話同步 |
getCreationTime() | 會話創建時間(毫秒級),可傳給 Date 構造函數格式化顯示 |
getLastAccessedTime() | 最後訪問時間,用於判斷用戶活躍度 |
getMaxInactiveInterval() | 獲取超時秒數,負值表示永不過期 |
getAttribute(name) | 獲取屬性值(JSP 1.0 為 getValue),需強制轉型 |
setAttribute(name, value) | 設置屬性(JSP 1.0 為 putValue),自動覆蓋同名舊值 |
removeAttribute(name) | 移除指定屬性 |
invalidate() | 銷毀會話,清除所有數據 |
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<%
session.setAttribute("username", "張三");
session.setAttribute("loginTime", new java.util.Date());
out.println("Session 數據已寫入,<a href='test2.jsp'>跳轉讀取</a>");
%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<%
String username = (String) session.getAttribute("username");
Date loginTime = (Date) session.getAttribute("loginTime");
if (username != null) {
out.println("歡迎:" + username + "<br>");
out.println("登入時間:" + loginTime + "<br>");
out.println("Session ID:" + session.getId());
} else {
out.println("Session 已失效或未登入");
}
%>
</body>
</html>
session.getAttribute("user") 實現權限控制Map<Integer, CartItem> 存儲商品信息session.invalidate() 再創建新會話