I have been a little confused about the use of sessions and Cookies, so I have a little request on my hand to learn about it when I use it.

Basic knowledge of

1. Since HTTP protocol is a stateless protocol, in order to remember the state of the request, the mechanism of Session and Cookie is introduced. 2.Session exists on the server side, which is managed by Tomcat in monolithic applications, while Cookie exists on the client side, which is more convenient to understand, and can be said to exist in the browser. 3. Cookies are just one way to implement sessions. Although it is the most common method, it is not the only one. 4. The process

  • First, the client sends an HTTP request to the server.
  • After the server accepts the client’s request, it establishes a session and sends an HTTP response to the client, which contains the Set-Cookie header. This header contains the SESSIONID.
  • In the second request made by the client, if the server gives a Set-Cookie, the browser will automatically add the Cookie to the request header
  • The server receives the request, decomposes the cookie, verifies the information, and returns the response to the client after checking the success

Code sample





1. If request.getSession() is not called, the server will never create the JSessionID. 2. If request.getSession() is called, the situation can be divided into the following two cases:

  • If this is the first time, request.getSession() creates a JSessionID and sets it in the response header:

Set-Cookie:JSESSIONID=********************************; Path=/; HttpOnly

  • If it is not the first visit, then this time the browser accesses the project, the request header will have:

Cookie: JSESSIONID = * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * request getSession () will be first to get the JSESSIONID request header, and find the ID in the server, If the session object is still alive (Tomcat defaults to a session of 30 minutes, after which the session object is destroyed), then the session object is acquired directly. If the session has already been destroyed, a new session object is created

Session in a distributed case

An ngxin load balancing access is used to illustrate the problem.

1. Start a nginx and load balance access to 8080 and 8081 services





2. First access to 8080, return set-cookies and sessionID command



3. Access getName interface. Due to load balancing of NGINX, access 8081



Because sessions were stored on Tomcat, and now there are two Tomcats, sessions are different!

Integration of spring – the session – data – redis







The first access to 8080 brings back the set-cookies command and the sessionID



Check the redis



Access the getName interface. Due to load balancing of NGINX, access to 8081 at this time, and no new session ID is regenerated at this time

Demo: https://github.com/WillLiaowh…