Cookie
- HTTP無狀態。Cookie記錄用戶訪問狀態。存放在客戶端。
- 用戶的通行證。
- 后臺的response寫入鍵值對數據。
- 用戶再次訪問帶上這個通行證。
- 檢查某個網站的Cookie:在瀏覽器地址欄輸入:
javascript:alert(document.cookie) - Cookie不可跨域
API: javax.servlet.http.Cookie
//to get cookie from client
Cookie[] cookies = request.getCookie();
// to write cookie 一個Cookie對象保存一個鍵值對
response.addCookie(Cookie cookie);
如下是Baidu的Cookie:
BaiduCookie.png
Session
- 服務器端記錄客戶端的訪問狀態
- 存放在服務器端的“客戶明細表”
- 每個來訪者對應一個Session對象
- JSP 內置Session隱藏對象
- <% page session="false" %> 則JSP中Session對象不可用
API: javax.servlet.http.HttpSession
// get session object.
HttpSession session = request.getSession();
// set session attribute
session.setAttribute("logintime", new Date());
// get session attribute
session.getAttribute("logintime");
// Attention to difference.
request.getSession(boolean create); // true 創建Session之后再返回
request.getSession(); //返回session,不存在則返回null。