[Java Web Series] Principle Analysis and Usage Details of Cookies

Continue to create, accelerate growth! This is the third day of my participation in the "Nuggets Daily New Plan · June Update Challenge", click to view the details of the event

1. Analysis of Cookie Principle

The implementation principle of cookies is based on the HTTP protocol , which involves the request header and response header information in the HTTP protocol:

  • Response headers :set-cookie
  • Request header :cookie

image-20220527232940263

  1. When the client browser accesses the server, the server sends the data information to the browser by adding Set-Cookie in the HTTP response. 响应头字段
  2. After the browser obtains the response result, it can obtain the Set-Cookiecorresponding value from the response header, and save the cookie in the browser memory or on the hard disk.
  3. When the server is requested again, the browser sends the cookie back to the web server by adding a cookie to the HTTP request message. 请求头字段
  4. The server tracks the status of the client according to the cookie information, and the Request object encapsulates the value corresponding to the cookie in the request header into a cookie object, and finally forms a cookie array
  • Send a cookie to the browser

image-20220505150650460

  • Get cookies from browser cache

image-20220505150558851

2. Cookie usage details

1️⃣Cookie life time

By default, cookies are stored in browser memory. When the browser is closed and the memory is released, the cookies are destroyed, that is, session-level cookies.

Set cookie storage time

  • Set the cookie survival time, that is, the persistent cookie , at this time the cookie is stored 电脑磁盘on the
// 单位:秒
setMaxAge(int seconds)
复制代码
  • Parameter setting details of seconds
  1. 正数:将Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除

  2. 负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁

  3. :使用 setMaxAge(0) 手动删除 Cookie时,需要使用 setPath 方法指定 Cookie 的路径,且该路径必须与创建 Cookie 时的路径保持一致

2️⃣Cookie存储中文

默认Cookie不能存储中文,直接传入中文会报500的错误

image-20220505153208266

解决方案

  1. 在AServlet中对中文进行URL编码,采用URLEncoder.encode(),将编码后的值存入Cookie中

  2. 在BServlet中获取Cookie中的值,获取的值为URL编码后的值

  3. 将获取的值在进行URL解码,采用URLDecoder.decode(),就可以获取到对应的中文值

示例

  1. 在Servlet1中对中文进行URL编码
@WebServlet("/c1")
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.对中文进行UTF-8编码
        String username = "倔强的牛角";
        String encodeUserName = URLEncoder.encode(username, StandardCharsets.UTF_8);
        // 2.创建cookie对象,存入编码后的中文
        Cookie c1 = new Cookie("username", encodeUserName);
        Cookie c2 = new Cookie("password", "123456");
        // 3.设置存活时间,1周 7天
        c1.setMaxAge(60*60*24*7);
        c2.setMaxAge(60*60*24*7);
        // 4.向浏览器发送cookie
        response.addCookie(c1);
        response.addCookie(c2);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
复制代码
  1. 在Servlet2中获取值,并对值进行解码
@WebServlet(name = "CookieDemo", value = "/c2")
public class CookieDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.获取cookie数组
        Cookie[] cookies = request.getCookies();
        // 2.遍历数组
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if ("username".equals(cookieName)) {
                // 对中文进行UTF-8解码
                String decodeUserName = URLDecoder.decode(cookieValue, StandardCharsets.UTF_8);
                System.out.println("key:" + cookieName + ",value:" + decodeUserName);
                continue;
            }
            System.out.println("key:" + cookieName + ",value:" + cookieValue);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
复制代码
  1. 演示结果
  • 存储到浏览器的是编码后的中文

image-20220505160653985

  • 获取编码的中文,并解码

image-20220505160557661

三、Cookie的缺点

Cookie 虽然可以解决服务器跟踪用户状态的问题,但是它具有以下缺点:

  • 在 HTTP 请求中,Cookie 是明文传递的,容易泄露用户信息,安全性不高
  • 浏览器可以禁用 Cookie,一旦被禁用,Cookie 将无法正常工作。
  • Cookie 对象中只能设置文本信息(字符串)信息。
  • 客户端浏览器保存 Cookie 的数量和长度是有限制的。

Guess you like

Origin juejin.im/post/7102440383598526477