session 是 Web 應用實現有狀態交互的核心機制,本文系統講解 session 對象 API、生命周期控制、登錄驗證典型場景及常見陷阱。
javax.servlet.http.HttpSession 實例
| 方法 | 說明 | 注意事項 |
|---|---|---|
| getId() | 獲取唯一會話標識 JSESSIONID | 只讀,容器生成 |
| setAttribute(name, value) | 存儲會話屬性 | value 必須可序列化(分布式環境) |
| getAttribute(name) | 獲取屬性,無則返回 null | 需類型轉換 |
| removeAttribute(name) | 移除指定屬性 | |
| invalidate() | 銷毀整個會話 | 登出操作必調用 |
| setMaxInactiveInterval(seconds) | 設置超時時間(秒) | 覆蓋 web.xml 默認值 |
| getMaxInactiveInterval() | 獲取當前超時設置 | |
| isNew() | 判斷是否新創建的會話 | 客戶端未攜帶 JSESSIONID 時為 true |
查閱 API 時忽略標註 @Deprecated 的方法(如 getValue()/putValue()),統一使用 Attribute 系列方法。
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if (userService.login(username, password)) {
session.setAttribute("loginUser", username); // 存入會話
session.setMaxInactiveInterval(30*60); // 30分鐘超時
response.sendRedirect("main.jsp");
} else {
out.println("用戶名或密碼錯誤");
}
%>
<%
if (session.getAttribute("loginUser") == null) {
response.sendRedirect("login.jsp?error=未登錄");
return;
}
%>
<%
session.invalidate(); // 徹底銷毀會話
response.sendRedirect("login.jsp");
%>