Cookie (super detailed)

Cookie Cookies

1. What is a cookie?

  1. Cookie translates to cookies.
  2. Cookie is a technology used by the server to notify the client to save key-value pairs .
  3. After the client has a cookie, each request is sent to the server.
  4. The size of each cookie cannot exceed 4kb

2. How to create a cookie

Insert picture description here

The code in the servlet program:

public class CookieServlet extends BaseServlet {
    
    
    protected void createCookie (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1 创建 cookie 对象
        Cookie cookie = new Cookie("key1","value1");
        //2 通知客户端保存 Cookie
        resp.addCookie(cookie);

        resp.getWriter().write("Cookie创建成功");
    }
}

Note: resp.addCookie(cookie); must not be less

3. How does the server get cookies

Cooike is stored on the client

How does the server get cookies?
The server only needs one line of code to get the client's cookies: req.getCookies() ===> The return value is an array Cookie[]

Cookie[] cookies = req.getCookies();

Insert picture description here

In a general project, get a specific cookie:

Cookie tools:

/**
 * 查找指定名称的Cookie对象
 * @param name
 * @param cookies
 * @return
 */
public static Cookie findCookie(String name , Cookie[] cookies){
    
    
    if (name == null || cookies == null || cookies.length == 0) {
    
    
        return null;
    }
    for (Cookie cookie : cookies) {
    
    
        if (name.equals(cookie.getName())) {
    
    
            return cookie;
        }
    }
    return null;
}

The code in the servlet program:

protected void getCookie (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        Cookie[] cookies = req.getCookies();

        for (Cookie cookie : cookies) {
    
    
            // getName 方法返回 Cookie 的 key (名称)
            // getValue 方法返回 Cookie 的 value 值
            resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
        }

        Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
//        for (Cookie cookie : cookies) {
    
    
//            if ("key2".equals(cookie.getName())) {
    
    
//                iWantCookie = cookie;
//                break;
//            }
//        }
          // 如果不等于 null,说明赋过值,也就是找到了需要的 Cookie
        if (iWantCookie != null) {
    
    
            resp.getWriter().write("找到了需要的 Cookie");
        }
    }

4. Modification of Cookie Value

Option One:

  1. First create a Cookie object with the same name (referring to the key) to be modified
  2. In the constructor, assign a new cookie value at the same time
  3. 调用 response.addCookie( Cookie );

Program in Servlet:

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        方案一:
//        1、先创建一个要修改的同名的Cookie对象
//        2、在构造器,同时赋于新的Cookie值。
        Cookie cookie = new Cookie("key1","newValue1");
//        3、调用response.addCookie( Cookie ); 通知 客户端 保存修改(没有这一行将没有用)
        resp.addCookie(cookie);

        resp.getWriter().write("key1的Cookie已经修改好");
    }

First create a Cookie:

Insert picture description here

After modification:

Insert picture description here

In Network: There is a Set-Cookie
Insert picture description here

After receiving the response, I found that there is a Set-Cookie response header, just go and check if there is a cookie, create it if it doesn’t exist, and modify it if it exists (see 2. How to create a cookie)

Option II:

  1. First find the cookie object that needs to be modified
  2. Call setValue() to assign a new cookie value
  3. Call response.addCookie() to notify the client to save the changes
//        方案二:
//        1、先查找到需要修改的Cookie对象
        Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());
        if (cookie != null) {
    
    
//        2、调用setValue()方法赋于新的Cookie值。
            cookie.setValue("newValue11");
//        3、调用response.addCookie()通知客户端保存修改
            resp.addCookie(cookie);
        }

5. Browser view Cookie:

How to view cookies in Google Chrome:

Insert picture description here

How to view cookies in Firefox:

Insert picture description here

6. Cookie life control

Cookie life control refers to how to manage when cookies are destroyed (deleted)

setMaxAge()
is a positive number, which means it will expire after the specified number of seconds. A
negative number means that the cookie will be deleted when the browser is closed (the default value is -1).
Zero means that the cookie will be deleted immediately

Session-level cookies:

/**
 * 默认的会话级别的Cookie
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    Cookie cookie = new Cookie("defalutLife","defaultLife");
    cookie.setMaxAge(-1);//设置存活时间,负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
    resp.addCookie(cookie);
}

Run show:

Insert picture description here

The survival time Max-Age of the defaluLife created here is displayed as Session, which is the session level.

We will find that the survival time of key1 we created before is also Session, the reason is:

In the source code, maxAge defaults to -1
Insert picture description here

Delete a cookie immediately:

/**
 * 马上删除一个Cookie
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    // 先找到你要删除的Cookie对象
    Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());
    if (cookie != null) {
    
    
        // 调用setMaxAge(0);
        cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
        // 调用response.addCookie(cookie);
        resp.addCookie(cookie);

        resp.getWriter().write("key1的Cookie已经被删除");
    }
}

Set a cookie that lasts for 1 hour:

/**
 * 设置存活1个小时的Cookie
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    Cookie cookie = new Cookie("life3600", "life3600");
    cookie.setMaxAge(60 * 60); // 设置Cookie一小时之后被删除。无效
    resp.addCookie(cookie);
    resp.getWriter().write("已经创建了一个存活一小时的Cookie");
}

7. Cookie effective path Path setting

The cookie path attribute can effectively filter which cookies can be sent to the server and which ones are not.
The path attribute is used to effectively filter by the requested address.

CookieA path=/Project path
CookieB path=/Project path/abc

The request address is as follows:
http://ip:port/project path/a.html
CookieA sends
CookieB does not send

​ http://ip:port/project path/abc/a.html
​ CookieA sending
​ CookieB sending

protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    Cookie cookie = new Cookie("path1", "path1");
    // getContextPath() ===>>>>  得到工程路径
    cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>>  /工程路径/abc
    resp.addCookie(cookie);
    resp.getWriter().write("创建了一个带有Path路径的Cookie");
}

At this time, we visited http://localhost:8080/13_cookie_session/cookie.html, clicked the cookie path setting, and found that the cookie we created could not be found in the console.

In the request header:

Insert picture description here

We found that Set-Cookie has been set, but the path is: Path=/13_cookie_session/abc

We did not match his path, so this cookie was filtered out by Google Chrome, making it invisible to us

At this time we visit again: http://localhost:8080/13_cookie_session/abc/cookie.html

At this time you can see the Cookie we created:

Insert picture description here

8. Cookie practice-login without entering a user name

Insert picture description here

login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
        用户名:<input type="text" name="username" value="${ cookie.username.value }"> <br>
        密码:<input type="password" name="password" id=""> <br>
        <input type="submit" value="登陆">
    </form>
</body>
</html>

LoginServlet.java:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    if ("aaa123".equals(username) && "123456".equals(password)) {
    
    
        //登陆成功
        Cookie cookie = new Cookie("username", username);
        cookie.setMaxAge(60 * 60 * 24 * 7); //当前 Cookie 一周内有效
        resp.addCookie(cookie);
        System.out.println("登陆成功!!!");
    } else {
    
    
        System.out.println("登陆失败~~~");
    }
}

In this way, as long as you enter the correct user name and password once, the next time you log in, you do not need to enter the user name, so that you can avoid entering the user name.

Guess you like

Origin blog.csdn.net/weixin_45024585/article/details/112748777