[what are cookies and sessions]

Posted by R0d Longfella on Thu, 23 Sep 2021 09:00:41 +0200

Cookie

What is a Cookie?

A Cookie is a piece of valid information obtained by the browser when accessing the server. After the browser obtains the Cookie, it will be saved to the local disk. As long as the Cookie is still valid, it will automatically carry the Cookie to the server when accessing the server again.

What's the use of cookies?

Cookie s can store information that needs to be used many times when accessing the server, such as user information, permissions, session time, etc.

Cookie features:

1) Non cross domain
2) Chinese will be garbled when stored
3) Period of validity
4) Only string key value pairs can be stored

Code example

package com.peko.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

@RestController
public class MyController {

    @RequestMapping("/cookieSet")
    public void cookieSet(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        Cookie cookie = new Cookie("username","jack");
        cookie.setMaxAge(5);   //Unit: Second
//        cookie.setMaxAge(-1);  // If it is set to a negative number, the Cookie is temporary and expires after closing the browser
//        cookie.setMaxAge(0);   // If it is set to 0, the Cookie will be deleted
        response.addCookie(cookie);
    }

    @RequestMapping("/cookieGet")
    public String cookieGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        String value = "";
        for(int i=0;cookies != null && i<cookies.length;i++){
            String name = cookies[i].getName();
            value = URLDecoder.decode(cookies[i].getValue(),"UTF-8");

        }
        //If you want to modify the Cookie, you should overwrite it
//        Cookie cookie = new Cookie("username","jack1111");
//        cookie.setMaxAge(5);
//        response.addCookie(cookie);

        return value;
    }
}

First access "/ cookieSet"

Then visit "/ cookieGet"


Session

What is Session?

Session is a mechanism for the server to store browser access information. As long as the session object is not destroyed, servlets (i.e. applications) can communicate through the session object.

What's the use of Session?

When the user data needs to be saved, the server program can write the user data to the session exclusive to the user's browser. When the user uses the browser to access other programs, other programs can take the user's data from the user's session to serve the user.

Session features:

1) Can store objects
2) The timeout time of a Session is 30 minutes by default. After the timeout, the Session will be deleted. When accessing a Session without timeout, the Session will update the timeout time
3) Use cookies to distinguish each browser user: the server will send a Cookie to the browser, in which there is a JESSIONID value. The server will distinguish each browser according to this. The maxAge value of the Cookie is - 1 by default, which is why after closing the browser, the server will not find the previous Session again.

Code example

package com.peko.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

@RestController
public class MyController {

    @RequestMapping("/sessionSet")
    public void sessionSet(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.setAttribute("number","123455");

//          Set the maximum Session timeout to 60 seconds. The unit here is seconds
//          session.setMaxInactiveInterval(60);
    }

    @RequestMapping("/sessionGet")
    public void sessionGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String number = (String)session.getAttribute("number");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("obtain session Medium number: "+number);
    }
}

First access "/ sessionSet"

Then access "/ sessionGet"

Recommended blog posts:
https://mp.weixin.qq.com/s?__biz=MzI4Njg5MDA5NA==&mid=2247484755&idx=6&sn=3a370551b0ee800f3bcad8ff37a72b9d&chksm=ebd74452dca0cd44f454ca8aa006d352c6994bb7ea955b5ca5f2ec2b227792010939bfa25532###rd
https://mp.weixin.qq.com/s?__biz=MzI4Njg5MDA5NA==&mid=2247484755&idx=7&sn=fb35232f3c15e2b4336498ac9f8804f1&chksm=ebd74452dca0cd44942721a159088a2f286d4e5c5f2bcdc7e264f0dccc8f9928d66858e475d4###rd
https://www.cnblogs.com/xdp-gacl/p/3855702.html

Topics: Session Spring Boot cookie