Java Web Cookie details

What is a cookie?

Query Youdao Dictionary:

What does the Web have to do with cookies?

The answer to this riddle and so on

Session technology

Session technology in the Web is similar to a real life chat between two people, except that a session in the Web refers to the interaction between a server and a client

A session consists of multiple requests and responses, established when the browser sends a request to the server, and ended when one party disconnects.functionWhat does it mean that data can be shared between multiple requests within the scope of a session

1. In browsers, there is often an exchange of data, such as when you log on to a page. We often set up automatic login options. So they remember our information through cookies, cookies are made by THE HTTP server, stored in the browser, but HTTP protocol is a stateless protocol, after the data exchange, the server and the client will be closed, each time the exchange of data need to establish a new link. Just like when we go to the supermarket to buy something without the integral card, after we buy something, the supermarket does not have any of our consumption information, but after we get the integral card, the supermarket has our consumption information. Cookies are like scorecards, which can save points. Goods are our information. The supermarket system is like the server background, and HTTP protocol is the transaction process.

2. Many websites now use new users to register this, sometimes register, wait until the next visit to the site, will automatically recognize you, and post to say hello to you, do not feel very cordial? Of course, such a function of knowledge surface phenomenon, more importantly, the website can use cookies to track the habits of users to visit the website, such as when to visit, which pages to visit, stay in each page and so on. Using this information, on the one hand, can provide personalized services for users, on the other hand, can also be used as a tool to understand all user behavior, for the improvement of website business strategy has certain reference value. , for example, you are in an airline site check flight schedule, the site might be created containing your Cookies, travel plan might it only recorded the you once visited Web pages on the site, when the next time you visit, to the content of the website according to your circumstance to adjust, on top of the content of the you’re interested in. This is an advanced COokie application.

The concept of cookies

Is a client session technique that saves data to the client

The advantages and disadvantages of cookies are as follows: 1. It is very convenient to save the data to the client and reduce the storage pressure of the server. 2. Limits on the number (20) and size (4KB) of data to be saved

Function cookie is used to save a small amount of and less sensitive data can be in the case of no login, to complete the identity of the client (that is, set a set-cookie key-value pair on the client, use key-value pair to obtain the identity of the client when accessing)

How to use cookies

I introduce the use of cookie from the following three steps: 1. Create cookie object 2. 3. Get the cookie. The cookie is set by Servlet1, and Servlet2 gets the cookie

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 a 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); }}Copy the code

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 a cookie
     Cookie[] cookies = req.getCookies();
     if(cookies! =null) {for (Cookie cookie : cookies) {
             // Get the cookie value and name
             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); }}Copy the code

In response to a cookie

Request cookies, the other two cookies we won’t cover here

Illustration:

Questions about cookies

How to send multiple cookies 2. How long can cookies be saved in the browser 3. How to save Cookies in Chinese 4

1. How to send multiple cookies

The cookie can be sent by calling the addCookie method using the Response object

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 a cookie
        // Create the first cookie
        Cookie cookie = new Cookie("name"."zhangsan");
        // Send the first cookie
        resp.addCookie(cookie);
        // Create a second cookie
        Cookie id = new Cookie("id"."1");
       // Send the second cookie
        resp.addCookie(id);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp); }}Copy the code
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 a cookie
     Cookie[] cookies = req.getCookies();
     // Iterate over the cookie array
     if(cookies! =null) {for (Cookie cookie : cookies) {
             // Get the cookie value and name
             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); }}Copy the code

Client display The IDEA of printing

2. How long can cookies be saved in the browser

Setmaxage (int seconds) setMaxage (int seconds) setMaxage (int seconds) setMaxage (int seconds) Second is less than zero. The default value is that the cookie is deleted after the browser is closed

3. How to save cookies in Chinese

  • Before Tomcat 8, Chinese data could not be stored directly in cookies.

Need to transcode Chinese data — generally URL encoding (%E3)

  • After Tomcat 8, cookies support Chinese data.

Special characters are still not supported. You are advised to use URL encoding for storage and URL decoding and parsing

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

Cookie cookie = new Cookie("name"."Zhang");
    // Send the first cookie
    resp.addCookie(cookie);
Copy the code

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 message body of the response
       resp.setContentType("text/html; charset=utf-8");
        / / create a cookie
        // Create the first cookie
        String name="Zhang";
        / / 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); }}Copy the code
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 a cookie
     Cookie[] cookies = req.getCookies();
     // Iterate over the cookie array
     if(cookies! =null) {for (Cookie cookie : cookies) {
             // Get the cookie value and name
             String value = cookie.getValue();
             String name = cookie.getName();
             / / 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); }}Copy the code

Results:

No longer an error

4.Cookie sharing problem

By default, cookies cannot be shared among web projects deployed on a Tomcat server. However, we can call setPath () to set the cookie range. By default, the current virtual directory is set. You can set path to “/”

 // Set the data format and encoding of the message body of the response
       resp.setContentType("text/html; charset=utf-8");
        / / create a cookie
        // Create the first cookie
        String name="张   三";
        / / URL encoding
        name= URLEncoder.encode(name,"utf-8");
        Cookie cookie = new Cookie("name", name);
        // Set path to share cookie information with all projects deployed under the current server
        // Set it to "/" to share
        cookie.setPath("/");
        resp.addCookie(cookie);
Copy the code
  1. Cookie sharing problem between different Tomcat servers? * setDomain(String path): If the first level domain is set to the same, Therefore, cookies can be shared between multiple servers * setDomain(“.baidu.com”), and cookies can be shared between tieba.baidu.com and news.baidu.com

   // Set the data format and encoding of the message body of the response
       resp.setContentType("text/html; charset=utf-8");
        / / create a cookie
        // Create the first cookie
        String name="张   三";
        / / URL encoding
        name= URLEncoder.encode(name,"utf-8");
        Cookie cookie = new Cookie("name", name);
        // Set path so that cookie information can be shared between different servers
        // If the domain name is ".baidu.com", cookies can be shared
       cookie.setDomain(".baidu.com");
        resp.addCookie(cookie);
Copy the code

If there are mistakes, please also criticize and correct, writing is not easy, like also please point a like, if there are questions, comments, I will often update the article, read the article feel helpful can pay attention to me