How to Use the Cookies in Spring Boot

How to Use the Cookies in Spring Boot

I. Introduction

This article outlines

  • Read HTTP Cookie
  • Set HTTP Cookie
  • Read all cookies []
  • Set the expiration time of Cookie
  • Https与Cookie
  • HttpOnly Cookie
  • Delete Cookie

HTTP Cookie (also called Web the cookie , browser the cookie ) is a small part of the data stored in the server user's browser. Server-side application set a cookie, the browser stores the cookie back to the browser request response time and the next time they are automatically transmitted together with a request back to the server side application.

Cookies provide a way to exchange information between the server and the browser to manage the session (login, shopping cart, game scores), to remember user preferences (themes, privacy policy accepted) and track user behavior throughout the site. Cookies certain extent, the liberation of the server-side pressure, because part of the data stored on the browser, so this part of the data can not be involved in the application of data security. In this article, we will learn how to read in Spring Boot applications, settings, and delete HTTP cookie.

Spring framework provides @CookieValueannotations to obtain the value of the HTTP cookie, this annotation can be used directly in the controller in method parameters.



@GetMapping("/")
public String readCookie(@CookieValue(value = "username", 
                                      defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}

In the above code segment, please note defaultValue = "Atta". If you do not set the default value for the username and did not find the name of Cookie, Spring will throw java.lang.IllegalStateExceptionan exception.

To set a cookie in Spring Boot, we can use the HttpServletResponsemethods of the class addCookie(). You need to do is create a new Cookieobject and add it to the response.


@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
    // 创建一个 cookie对象
    Cookie cookie = new Cookie("username", "Jovan");

    //将cookie对象加入response响应
    response.addCookie(cookie);

    return "Username is changed!";
}

Fourth, read all Cookie []

In addition to using @CookieValueannotations, we can also use the HttpServletRequestclass as a method parameter controller to read all the cookie. This class provides a getCookies()method, which returns all cookie sent by the browser as an array.


@GetMapping("/all-cookies")
public String readAllCookies(HttpServletRequest request) {

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        return Arrays.stream(cookies)
                .map(c -> c.getName() + "=" + c.getValue())
                .collect(Collectors.joining(", "));
    }

    return "No cookies";
}

Fifth, set an expiration time of Cookie

If you do not specify an expiration time for the cookie, then its life cycle will continue until the Session expired. Such a cookie is called a session cookie . Session cookie remains active until the user closes their browser or clear its cookie. But you can override this default behavior and use the class setMaxAge()method to set the cookie expiration time.


// 创建一个 cookie对象
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // 7天过期

//将cookie对象加入response响应
response.addCookie(cookie);

Now, usernameCookie will not end Seesion expire, but will remain valid for the next seven days. Passed to the setMaxAge()method expiry time in seconds. Expiration date and time is relative to set a cookie rather than in terms of client server.

Six, Https and Cookie

We need to understand a concept: What is the security of Cookies? The security cookie is only sent to the cookie server can be connected via an encrypted HTTPS. Unable to connect to the server to send the cookie unencrypted HTTP. In other words, if you set setSecure (true), the Cookie will not be transmitted Http connected, only Https connection transmission.


// 创建一个 cookie对象
Cookie cookie = new Cookie("username", "Jovan");
cookie.setSecure(true);  //Https 安全cookie

//将cookie对象加入response响应
response.addCookie(cookie);

HttpOnly cookie is used to prevent cross-site scripting (XSS) attacks, that is set Http Only the Cookie can not be the JavaScript Document.cookieAPI access, only in the end by the server to access the service.


// 创建一个 cookie对象
Cookie cookie = new Cookie("username", "Jovan");
cookie.setHttpOnly(true);  //不能被js访问的Cookie

//将cookie对象加入response响应
response.addCookie(cookie);

Eight, delete Cookie

To delete a Cookie, you need to be Max-Ageset to 0, and the value of Cookie is null. Do not Max-Agecommand value to -1a negative number. Otherwise, the browser treats it as a session cookie.


// 将Cookie的值设置为null
Cookie cookie = new Cookie("username", null);
//将`Max-Age`设置为0
cookie.setMaxAge(0);

response.addCookie(cookie);

Look forward to your attention

Guess you like

Origin www.cnblogs.com/zimug/p/11785225.html