Spring MVC Getting Started Guide (13): Getting Cookie Values

Commonly used session tracking technologies are cookies and sessions. Cookie determines user identity by recording information on the client side , and Session determines user identity by recording information on the server side .


1. Cookie   mechanism

In programs, session tracking is a very important thing. In theory, all request operations of one user should belong to the same session , and all request operations of another user should belong to another session. The two should not be confused. For example, any product purchased by user A in the supermarket should be placed in A's shopping cart. No matter when user A purchased it, it belongs to the same session and cannot be placed in user B's or user C's shopping cart. , which do not belong to the same session.

Web applications, on the other hand, use the HTTP protocol to transfer data. The HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server is closed, and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection . That is, when user A buys a product and puts it into the shopping cart, the server cannot determine whether the purchase belongs to the session of user A or the session of user B when the product is purchased again. To keep track of this session, a mechanism must be introduced.

Cookies are one such mechanism. It can make up for the lack of statelessness of the HTTP protocol. Before the advent of Session, basically all websites used cookies to track sessions.


2. What are cookies 

Cookie means "sweet cookie", which is a mechanism proposed by the W3C organization and first developed by the Netscape community. At present, cookies have become a standard, and all major browsers such as IE, Netscape, Firefox, Opera, etc. support cookies.

Since HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. How to do it? Just issue a pass to the clients, one for each person, and whoever visits must bring their own pass. This allows the server to verify the client's identity from the passport. This is how cookies work .


3. Set all the properties of the cookie

Cookie common attributes

property name

Depiction

String name

The name of this cookie. Once the cookie is created, the name cannot be changed

Object value

The value of this cookie. If the value is a Unicode character, it needs to be the character encoding. If the value is binary data, you need to use BASE64 encoding

int maxAge

The expiration time of the cookie, in seconds. If positive, the cookie expires after maxAge seconds. If it is a negative number, the cookie is a temporary cookie, which will be invalid after closing the browser, and the browser will not save the cookie in any form. If it is 0, it means to delete the cookie. Defaults to –1

boolean secure

Whether the cookie is only transmitted using a secure protocol. Security Protocol. Security protocols include HTTPS, SSL, etc., which encrypt data before transmitting it on the network. Default is false

String path

The usage path of this cookie. If set to "/sessionWeb/", only programs whose contextPath is "/sessionWeb" can access the cookie. If it is set to "/", the contextPath under this domain name can access the cookie. Note that the last character must be "/"

String domain

The domain name that can access the cookie. If set to ".google.com", all domains ending in "google.com" can access the cookie. Note that the first character must be "."

String comment

Description of the purpose of this cookie. This description is displayed when the browser displays the cookie information

int version

The version number used by this cookie. 0 means follow Netscape's cookie specification, 1 means follow W3C's RFC 2109 specification


4. Cookie validity period

The maxAge of the cookie determines the validity period of the cookie, and the unit is Second. In Cookie, the maxAge attribute is read and written through the getMaxAge() method and the setMaxAge(int maxAge) method.

If the maxAge attribute is a positive number, it means that the cookie will automatically expire after maxAge seconds. The browser will persist the cookie whose maxAge is a positive number, that is, write it to the corresponding cookie file. Regardless of whether the customer closes the browser or the computer, the cookie is still valid when logging in to the website as long as it is before maxAge seconds. The cookie information in the code below will always work.


5. Modification and deletion of cookies

Cookies do not provide modification and deletion operations. If you want to modify a cookie, you only need to create a new cookie with the same name and add it to the response to overwrite the original cookie.

If you want to delete a cookie, you only need to create a new cookie with the same name, set maxAge to 0, and add it to the response to overwrite the original cookie. Note that it is 0 and not a negative number. Negative numbers have other meanings. Readers can verify and set different properties through the program in the above example.

Note: When modifying or deleting a cookie, all attributes of the newly created cookie except value and maxAge, such as name, path, domain, etc., must be exactly the same as the original cookie. Otherwise, the browser will consider that two different cookies will not be covered, resulting in the failure of modification and deletion.


6. Security properties of cookies

The HTTP protocol is not only stateless, but also insecure. Data using the HTTP protocol is directly transmitted on the network without any encryption, and may be intercepted. Using the HTTP protocol to transmit very confidential content is a hidden danger. If you do not want cookies to be transmitted in non-secure protocols such as HTTP, you can set the secure attribute of cookie to true. Browsers will only transmit such cookies in secure protocols such as HTTPS and SSL. The following code sets the secure property to true:

Cookie cookie = new Cookie("time", "20080808"); // 新建Cookie

cookie.setSecure(true); // set security properties

response.addCookie(cookie); // output to client

Tip: The secure attribute does not encrypt the cookie content, so absolute security cannot be guaranteed. If high security is required, the cookie content needs to be encrypted and decrypted in the program to prevent leakage.


7. Case -- get cookie value

    1.LoginController.java

/**
 * @author Ray
 * @date 2018/4/26 0026
 */
@Controller
@RequestMapping(value = "login")
public class LoginController {

    @RequestMapping(value = "doLogin")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "checkCookie")
    public String checkCookie(String username, String password, HttpServletResponse response){
        // create a new cookie
        Cookie username_cookie = new Cookie("username", username);
        Cookie password_cookie = new Cookie("password", password);
        // output to client
        response.addCookie(username_cookie);
        response.addCookie(password_cookie);
        return "redirect:getCookie";
    }

    @RequestMapping(value = "getCookie")
    public String getCookie(@CookieValue("username") String username, @CookieValue("password") String password){
        // console output
        System.out.println("username: " + username);
        System.out.println("password: " + password);
        return "success";
    }
}

    2.login.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Login interface</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <form action="login/checkCookie" method="post">
        <table>
            <th>Login interface</th>
            <tr>
                <td>姓名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="text" name="password"></td>
            </tr>
            <tr>
                <td><input type="submit" value="登录"></td>
            </tr>
        </table>
    </form>
</body>
</html>

    3.success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Cookie</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <h2>Get Cookies</h2>
    username_cookie:${cookie.username.value}<br>
    password_cookie:${cookie.password.value}
</body>
</html>

    4. Test run



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325405595&siteId=291194637