Cookie原理

Mike-H發表於2020-11-24

1. 概念:客戶端會話技術,將資料儲存到客戶端

功能:在一次會話的範圍內的多次請求間,共享資料一次會話可以多次請求和響應的

2. 快速入門:

  • 使用步驟:
  1. 建立Cookie物件,繫結資料
  • new Cookie(String name, String value)
  1. 傳送Cookie物件(伺服器傳送給瀏覽器,然後瀏覽器就儲存改cookie,下次請求伺服器時(比如訪問ServletCookiedemo2),會攜帶這個cookie去請求伺服器
  • response.addCookie(Cookie cookie)
  1. 獲取Cookie,拿到資料(由於瀏覽器攜帶cookie來訪問伺服器的某個資源(eg:某個servlet類),所以用resquest獲取它請求的cookie資訊
  • Cookie[] request.getCookies()

定義兩個servlet類:
ServletCookiedemo1:

package cn.itcast.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author QLBF
 * @version 1.0
 * @date 2020/11/24 19:10
 */
@WebServlet("/ServletCookiedemo1")
public class ServletCookiedemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.伺服器建立Cookie物件
        Cookie c=new Cookie("msg","hellocookie");
        //2.傳送Cookie給瀏覽器
        response.addCookie(c);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

ServletCookiedemo2:

package cn.itcast.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author QLBF
 * @version 1.0
 * @date 2020/11/24 19:10
 */
@WebServlet("/ServletCookiedemo2")
public class ServletCookiedemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //3. 獲取Cookie(獲取ServletCookiedemo1返回給伺服器的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);
    }
}

當瀏覽器訪問ServletCookiedemo1後,http://localhost:8080/bbb/ServletCookiedemo1(這裡虛擬目錄為bbb),再訪問http://localhost:8080/bbb/ServletCookiedemo2。控制檯會輸出:
在這裡插入圖片描述
這裡面可以獲取ServletCookiedemo1設定的鍵值,可以共享資料。

3. 實現原理

  • 基於響應頭set-cookie和請求頭cookie實現

在這裡插入圖片描述

相關文章