一、會話技術
-
會話:一次會話中包含多次請求和響應(同一個瀏覽器屬於一個會話,不同瀏覽器屬於不同會話)
一次會話:瀏覽器第一次給服務器資源發送請求,會話建立,直到有一方斷開爲止
-
功能:在一次會話的範圍內的多次請求間,共享數據
-
方式:
客戶端會話技術:Cookie
服務器端會話技術:Session
二、Cookie 快速入門
-
概念:客戶端會話技術,將數據保存到客戶端
-
使用步驟:
(1)創建Cookie對象,綁定數據
* new Cookie(String name, String value)
(2)發送Cookie對象
* response.addCookie(Cookie cookie)
(3)獲取Cookie,拿到數據,存在多個 Cookie,所以返回的是一個數組
* Cookie[] request.getCookies()
@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.創建Cookie對象
Cookie c = new Cookie("msg","hello");
//2.發送Cookie
response.addCookie(c);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//3. 獲取Cookie
Cookie[] cs = request.getCookies();
//獲取數據,遍歷Cookies
if(cs != null){
for (Cookie c : cs) {
String name = c.getName();
String value = c.getValue();
System.out.println(name+":"+value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}