HTTP 無狀態,JSP 透過 HttpSession 維持會話。資料存伺服器端,Session ID 存在客戶端 Cookie(或 URL Rewriting 备援)。預設逾時 30 分鐘,僅能存放物件(不可存基本型別如 int,需用 Integer)。
| 方法 | 說明 |
|---|---|
getId() | 唯一 Session 識別碼 |
getCreationTime() | 建立時間 (ms) |
getLastAccessedTime() | 最後存取時間 (ms) |
getMaxInactiveInterval() | 逾時秒數,負值=永不逾時 |
getAttribute(name) | 取得屬性值 (JSP 1.0 用 getValue) |
setAttribute(name, value) | 設定屬性,覆蓋舊值 (JSP 1.0 用 putValue) |
test1.jsp 寫入
<% session.setAttribute("str", new String("this is test")); %>
test2.jsp 讀取
<%
String ls_str = (String) session.getAttribute("str");
out.println("從 Session 取出的值:" + ls_str);
%>
瀏覽 test1 再瀏覽 test2 即可見輸出,驗證 Session 跨請求共享特性。