Detailed explanation of Java Web cookie (persistence + principle explanation + sharing problem + setting Chinese + sending multiple cookies)

Time:2020-9-6

Java Web cookie

What is a cookie?

According to Youdao Dictionary:

在这里插入图片描述
在这里插入图片描述

What does the web have to do with cookies?

在这里插入图片描述
This riddle will be revealed for you

Conversation Technology

The conversation technology in the web is similar to chatting between two people in life, but the conversation in the web refers to the interaction between the server and the client

A session contains multiple requests and responses. When the browser sends a request to the server, the session is established until one party is disconnected.
function: data can be shared between multiple requests within the scope of a session
What does that mean? I’ll explain it with a shopping cart
在这里插入图片描述

1. In the browser, data exchange is often involved, such as: you log in to a page. We often set the auto login option. Then they remember our information through cookies. Cookies are stored in the browser by the head of the HTTP server. However, HTTP protocol is a stateless protocol. After data exchange, the link between the server and the client will be closed, and a new link needs to be established every time the data is exchanged. Just like when we go to the supermarket to buy things, we don’t have any consumption information in the supermarket after we buy things, but after we do the points card, the supermarket will have our consumption information. Cookies are like a scorecard, which can save points. Commodities are our information. Supermarket systems are like server backstage. HTTP protocol is the process of transaction.

2. Many websites now use new users to register this item. Sometimes, when you register, you will be automatically recognized and posted to say hello to you when you visit the site next time. Do you feel very kind? Of course, this kind of knowledge surface phenomenon, more importantly, the website can use cookies to track and count the user’s habits of visiting the website, such as when to visit, which pages visited, and the time spent on each page. Using this information, on the one hand, can provide personalized services for users, on the other hand, it can also be used as a tool to understand the behavior of all users, which has a certain reference value for the improvement of website management strategy. For example, if you look up a flight schedule at an airline site, the site may create cookies containing your travel plans, or it may only record the web pages you have visited on the site. When you visit the next time, the website will adjust the content displayed according to your situation and put the content you are interested in at the top. This is an advanced cookie application.

在这里插入图片描述

The concept of cookie

Is a client session technology that saves data to the client

Advantages and disadvantages of cookies
1. It is very convenient to save the data to the client and reduce the storage pressure of the server
2. There are restrictions on the number (20) and size of stored data (4KB)

effect
Cookies are used to hold a small amount of data that is not very sensitive
The client can be identified without logging in (that is, a key value pair of set cookie is set in the client, and the key value pair is used to obtain the identity of the client when accessing)

How to use cookies

Let me introduce the use of cookies in the following three steps
1. Create cookie object
2. Send cookie object
3. Get the cookie object
The cookie is set by servlet1 and obtained by servlet2

Servlet1

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo1")
public class Servlet1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Create cookie
        Cookie cookie = new Cookie("name", "zhangsan");
        resp.addCookie(cookie);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Servlet2

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo2")
public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get cookie
     Cookie[] cookies = req.getCookies();
     if (cookies!=null){
         for (Cookie cookie : cookies) {
             //Get cookie值与名称
             String value = cookie.getValue();
             String name = cookie.getName();
             System.out.println(name+":"+value);
         }
     }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

Response cookie
在这里插入图片描述

在这里插入图片描述
Request cookie. We will not introduce the other two cookies here

在这里插入图片描述

graphic

在这里插入图片描述

Cookie related issues

1. How to send multiple cookies
2. How long can cookies be saved in the browser
3. How to save Chinese for cookies
4. Cookie sharing

1. How to send multiple cookies

Use the response object to call the addcookie method to send the cookie

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo1")
public class Servlet1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Create cookie
        //Create the first cookie
        Cookie cookie = new Cookie("name", "zhangsan");
        //Send first cookie
        resp.addCookie(cookie);
        //Create a second cookie
        Cookie id = new Cookie("id", "1");
       //Send a second cookie
        resp.addCookie(id);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo2")
public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get cookie
     Cookie[] cookies = req.getCookies();
     //Traverse cookie array
     if (cookies!=null){
         for (Cookie cookie : cookies) {
             //Get cookie值与名称
             String value = cookie.getValue();
             String name = cookie.getName();
             System.out.println(name+":"+value);
         }
     }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

Client display
在这里插入图片描述Idea printing
在这里插入图片描述

2. How long can cookies be saved in the browser

By default, cookie data is destroyed when the browser is closed
We can call the setmaxage (int seconds) method to set the storage time of the cookie
1. Second is a positive number. Write the cookie persistently to the hard disk and specify the storage time. When the time is up, the cookie will automatically become invalid
2. If second is zero, delete the cookie
3. If second is less than zero, the default value is to delete the cookie after the browser is closed

3. How to save Chinese for cookies

  • Before Tomcat 8, Chinese data could not be stored directly in cookies.
    Need to transcode Chinese data — URL encoding is generally used (% E3)
  • After Tomcat 8, cookies support Chinese data.
    Special characters are still not supported. It is recommended to use URL encoding storage and URL decoding and parsing

For example, if I use the following code to add data to a cookie, the browser will report an error because a space is added to the cookie

Cookie cookie = new cookie ("name", "Zhang San");
    //Send first cookie
    resp.addCookie(cookie);

在这里插入图片描述So I need to use URL encoding to control the data

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/demo1")
public class Servlet1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set the data format and encoding of the response message body
       resp.setContentType("text/html;charset=utf-8");
        //Create cookie
        //Create the first cookie
        String name = Zhang San;
        //URL encoding
        name= URLEncoder.encode(name,"utf-8");
        Cookie cookie = new Cookie("name", name);
        resp.addCookie(cookie);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

@WebServlet("/demo2")
public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get cookie
     Cookie[] cookies = req.getCookies();
     //Traverse cookie array
     if (cookies!=null){
         for (Cookie cookie : cookies) {
             //Get cookie值与名称
             String value = cookie.getValue();
             String name = cookie.getName();
             //Before decoding
             System.out.println(name+":"+value);
             //After decoding
             System.out.println(name+":"+ URLDecoder.decode(value,"utf-8"));
         }
     }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

result:

No more mistakes

在这里插入图片描述在这里插入图片描述

4. Cookie sharing

1. Suppose multiple web projects are deployed in a Tomcat server, how to share cookies in these projects
It is not shared by default
However, we can call the setpath() method to set the scope of the cookie. By default, the current virtual directory * can be set to “/” if you want to share it

//Set the data format and encoding of the response message body
       resp.setContentType("text/html;charset=utf-8");
        //Create cookie
        //Create the first cookie
        String name = Zhang San;
        //URL encoding
        name= URLEncoder.encode(name,"utf-8");
        Cookie cookie = new Cookie("name", name);
        //Set path to let all projects deployed under the current server share cookie information
        //Set to / to share
        cookie.setPath("/");
        resp.addCookie(cookie);
  1. Cookie sharing among different Tomcat servers? *Setdomain (string path): if the first level domain name is set to be the same, then multiple servers can share * setdomain (” baidu.com “), then tieba.baidu.com and news.baidu.com Cookies in can be shared
//Set the data format and encoding of the response message body
       resp.setContentType("text/html;charset=utf-8");
        //Create cookie
        //Create the first cookie
        String name = Zhang San;
        //URL encoding
        name= URLEncoder.encode(name,"utf-8");
        Cookie cookie = new Cookie("name", name);
        //Set the path so that cookie information can be shared between different servers
        //For example, set the domain name to " baidu.com "Can share cookies
       cookie.setDomain(".baidu.com");
        resp.addCookie(cookie);

If you have any mistakes, please criticize and correct me. It is not easy to write. If you like, please give me a like. If you have any questions, I will update the article frequently. If you feel helpful, you can pay attention to me

在这里插入图片描述

Recommended Today

Layout of angular material (2): layout container

Layout container Layout and container Using thelayoutDirective to specify the layout direction for its child elements: arrange horizontally(layout=”row”)Or vertically(layout=”column”)。 Note that if thelayoutInstruction has no value, thenrowIs the default layout direction. row: items arranged horizontally.max-height = 100%andmax-widthIs the width of the item in the container. column: items arranged vertically.max-width = 100%andmax-heightIs the height of the […]