Unveiling the mystery of Cookies and Sessions in JavaWeb

Insert image description here

1. Overview of session tracking technology

  • Session: The user opens the browser, accesses the resources of the web server, and the session is established until one party disconnects and the session ends. A session can containrepeatedlyRequests and responses.

    • After the browser makes a request and the server responds with data to the front end, a session (between the browser and the server) is established.
    • After the session is established, if neither the browser nor the server is closed, the session will continue to be established.
    • The browser and server can continue to use the session to send requests and respond. The entire process above is calledsession

    Thinking: How many sessions have been established in total in the picture below?

Insert image description here

Insert image description here

Why do multiple requests in a session need to share data? What functions can be achieved with this data sharing function?

  • The page displays user login information: For many websites, after logging in to access multiple functions and sending multiple requests, the browser will have the information [user name] of the currently logged in user, such as Baidu, JD.com, Code Cloud, etc.

Insert image description here

  • Function of the website login page记住我: When the user logs in successfully and checks the 记住我 button, the website will automatically Fill in the username and password to simplify the user's login operation. Multiple logins will result in multiple requests, and they also involve sharing data

Insert image description here

After analyzing the specific reasons, how to implement session tracking technology? The specific implementation methods are:

(1) Client session tracking technology:Cookie

(2) Server-side session tracking technology:Session

Both technologies can implement session tracking, and the biggest difference between them is:Cookies are stored on the browser side and Sessions are stored on the server side.
Insert image description here

2,Cookie

2.1 Basic use of cookies

1. Concept

Cookie: Client session technology saves data to the client, and each subsequent request carries cookie data for access.

2.Cookie workflow

Insert image description here

3.Basic use of cookies

Regarding the use of cookies, we should pay more attention to how the background code operates cookies. The operations of cookies are mainly divided into two categories. This isSend CookieandGet Cookie,How to implement the above two pieces of content respectively?

3.1 Sending Cookies

  • Create Cookie object and set data
Cookie cookie = new Cookie("key","value");
  • Send cookie to client: useresponseobject
response.addCookie(cookie);

Insert image description here

3.2 Get Cookies

  • To get all cookies carried by the client, userequestobject
Cookie[] cookies = request.getCookies();
  • Traverse the array and obtain each Cookie object: for
  • Get data using Cookie object methods
cookie.getName();
cookie.getValue();

2.2 Analysis of Cookie Principles

The implementation principle of Cookie is based on the HTTP protocol, in which two request header information in the HTTP protocol are designed:

  • Response header:set-cookie
  • Request header: cookie

Insert image description here

  • AServlet sends Cookie to the front end, and BServlet obtains the Cookie function from the request.

  • When Tomcat finds that the backend is returning a Cookie object, Tomcat will add a line of data to the response header==Set-Cookie:username=zs==

  • After the browser obtains the response result, it can obtain the corresponding valueSet-Cookie from the response headerusername=zs, and store the data in the browser's In memory

  • When the browser sends a request to the BServlet again, the browser will automatically add ==Cookie: username=zs== to the request header and send it to the server BServlet

  • The Request object will encapsulate the values ​​corresponding to the cookies in the request header into Cookie objects, eventually forming an array.

  • After BServlet obtains Cookie[] through the Request object, it can obtain the data it needs from it.

2.3 Cookie usage details

In this section, we mainly explain two pieces of knowledge. The first is the survival time of Cookie, and the second is how Cookie stores Chinese characters. First, let’s learn about the survival time of Cookie.

2.3.1 Cookie survival time

Insert image description here
Before sending a request to the BServlet, if the browser is closed and reopened for access, can the BServlet obtain the cookie data?

  • By default, cookies are stored in browser memory. When the browser is closed and the memory is released, the cookie is destroyed.

This conclusion confirms the above demonstration effect, but if you use this default cookie, some requirements cannot be achieved, such as:

Insert image description here

There is a function记住我 on the login page of the above website, which everyone is familiar with

So we now encounter a problem: how to store cookies persistently?

Cookie has actually provided us with the corresponding API to accomplish this. This API issetMaxAge,

  • Set cookie survival time
setMaxAge(int seconds)

Parameter values ​​are:

1. Positive number: Write the cookie to the hard disk of the computer where the browser is located for persistent storage. Automatically delete when time expires

2. Negative number: Default value, the cookie is in the current browser memory. When the browser is closed, the cookie is destroyed.

3. Zero: Delete the corresponding cookie
Insert image description here

2.3.2 Cookie storage Chinese

  • Cookies cannot directly store Chinese characters

Cookies cannot store Chinese characters, but if there is a need for this, how should we solve it at this time?

At this time, we can use a knowledge point we have learned before calledURL编码, so if we need to store Chinese, we need to transcode. The specific implementation idea is:

1. Encode Chinese URL in AServlet, use URLEncoder.encode(), and store the encoded value in Cookie

2. Obtain the value in the Cookie in BServlet. The obtained value is the URL-encoded value.

3. Perform URL decoding on the obtained value and use URLDecoder.decode() to obtain the corresponding Chinese value.

(1) URL encoding Chinese in AServlet

@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //发送Cookie
        String value = "黑洞晓威";
        //对中文进行URL编码
        value = URLEncoder.encode(value, "UTF-8");
        System.out.println("存储数据:"+value);
        //将编码后的值存入Cookie中
        Cookie cookie = new Cookie("username",value);
        //设置存活时间   ,1周 7天
        cookie.setMaxAge(60*60*24*7);
        //2. 发送Cookie,response
        response.addCookie(cookie);
    }

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

(2) Get the value in BServlet and decode the value

@WebServlet("/bServlet")
public class BServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取Cookie
        //1. 获取Cookie数组
        Cookie[] cookies = request.getCookies();
        //2. 遍历数组
        for (Cookie cookie : cookies) {
    
    
            //3. 获取数据
            String name = cookie.getName();
            if("username".equals(name)){
    
    
                String value = cookie.getValue();//获取的是URL编码后的值 %E5%BC%A0%E4%B8%89
                //URL解码
                value = URLDecoder.decode(value,"UTF-8");
                System.out.println(name+":"+value);//value解码后为 黑洞晓威
                break;
            }
        }

    }

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

At this point, we can store Chinese in Cookie for use.

Insert image description here

3,Session

Cookies can already complete data sharing between multiple requests in a session. We also mentioned that Sessions can also be implemented, then:

3.1 Basic use of Session

1. Concept

Session: Server-side session tracking technology: save data to the server.

  • Session is stored on the server side and Cookie is stored on the client side.
  • Data stored on the client is easily stolen and intercepted, and there are many unsafe factors.
  • Data stored on the server is more secure than on the client

2.Session workflow

Insert image description here

  • The AServlet on the server side obtains a Session object and stores the data in it.
  • The BServlet on the server side obtains the same Session object and retrieves data from it
  • This enables data sharing between multiple requests in a session.
  • The biggest question now is how to ensure that AServlet and BServlet use the same Session object (explained in the principle analysis session)?

3.Basic use of Session

  • Session acquisition

    HttpSession session = request.getSession();
    
  • Use of Common Session Methods

    void setAttribute(String name, Object o)
    Object getAttribute(String name)
    

    Note: What can be stored in Session is an Object type of data, which means that any data type can be stored in Session.

After introducing the basic use of Session, how does the underlying layer of Session realize data sharing between two requests in a session?

3.2 Principle analysis of Session

  • Session is implemented based on Cookie

In fact, this sentence cannot explain the underlying implementation of Session in detail. Next, let’s analyze the specific implementation principle of Session step by step:

(1) Prerequisites

Insert image description here

If Session wants to realize data sharing between multiple requests in a session, it must ensure that the Session object obtained by multiple requests is the same.

Then the main question comes, how does Session ensure that the Session object obtained in a session is the same?

Insert image description here

(1) When demo1 obtains the session object for the first time, the session object will have a unique identifier. If it isid:10

(2) After demo1 stores other data in the session and processes all business, it needs to respond to the browser through the Tomcat server.

(3) When the Tomcat server discovers that the session object is used in business processing, it will treat the session's unique identifierid:10 as a cookie and add Set-Cookie:JESSIONID=10 to in the response header and respond to the browser

(4) After the browser receives the response result, it will store the cookie data in the response header into the browser's memory.

(5) When the browser accesses demo2 in the same session, it will add the data in the cookie to the request header in the format of cookie: JESSIONID=10 and send it to the server Tomcat

(6) After demo2 obtains the request, it reads the JSESSIONID value in the cookie as 10 from the request header, and then searches for the session object of id:10 in the server memory. If it is found, return the object directly. If not, create a new session object

(7) After closing and opening the browser, because the browser's cookie has been destroyed, there is no JESSIONID data, and the session obtained by the server is a brand new session object.

summary

After introducing the principle of Session, we only need to remember

  • Session is implemented based on Cookie

3.3 Session usage details

In this section we will mainly explain two pieces of knowledge. The first is the passivation and activation of the Session, and the second is the destruction of the Session. First, let’s learn what is the passivation and activation of the Session?

3.3.1 Session passivation and activation

The first question that everyone needs to think about is:

  • After the server is restarted, is the data in the Session still there?

To answer this question, we can first look at the picture below,

Insert image description here

(1) The session object shared by server-side AServlet and BServlet should be stored in the server's memory.

(2) After the server is restarted, the data in the memory should have been released and the objects should have been destroyed.

So the session data should no longer exist.

So how is the session data saved when the Tomcat server is restarted?

The specific reason is: Passivation and activation of Session:

  • Passivation: After the server is shut down normally, Tomcat will automatically write the Session data to the file on the hard disk.

    • The passivated data path is:项目目录\target\tomcat\work\Tomcat\localhost\项目名称\SESSIONS.ser

      Insert image description here

  • Activation: After starting the server again, load data from the file into the Session

    • After the data is loaded into the Session, the SESSIONS.ser file in the path will be deleted

You just need to understand the entire process mentioned above. Because all the processes are completed by Tomcat itself, we do not need to participate.

summary

After introducing the passivation and activation of Session, we need to pay attention to the following:

  • Session data is stored on the server side. After the server is restarted, the session data will be saved.

  • After the browser is closed and started, the re-established connection is already a new session, and the session data obtained is also a new object.

  • If you want to share the session data, the browser cannot be closed, so the session data cannot be saved for a long time.

  • Cookies are stored on the client side and can be stored for a long time.

3.3.2 Session destruction

There are two ways to destroy a session:

  • By default, no operation is performed and it is automatically destroyed in 30 minutes.

    • This expiration time can be modified through configuration.

      • Configure in the project's web.xml

        <?xml version="1.0" encoding="UTF-8"?>
        <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
                 version="3.1">
        
            <session-config>
                <session-timeout>100</session-timeout>
            </session-config>
        </web-app>
        
      • If not configured, the default is 30 minutes. The default value is hard-coded in Tomcat's web.xml configuration file.

        Insert image description here

  • Call invalidate() of the Session object to destroy it

    • Add a session destruction method to the SessionDemo2 class

      @WebServlet("/demo2")
      public class SessionDemo2 extends HttpServlet {
              
              
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              
              
              //获取数据,从session中
      
              //1. 获取Session对象
              HttpSession session = request.getSession();
              System.out.println(session);
      
              // 销毁
              session.invalidate();
              //2. 获取数据
              Object username = session.getAttribute("username");
              System.out.println(username);
          }
      
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              
              
              this.doGet(request, response);
          }
      }
      
    • Start the access test, first visit demo1 to store data into the session, and then visit demo2 again to get data from the session.

      Insert image description here

    • This destruction method generally requires the session to be destroyed when the user exits.

Summary of Cookies and Sessions

  • Both Cookie and Session are used to complete multiple requests within a session.data sharingof.

To put the two required objects together, you need to think about:

What is the difference between Cookie and Session?

What are the application scenarios of Cookie and Session?

  • the difference:

    • Storage location: Cookie stores data on the client side, and Session stores data on the server side.
    • Security: Cookie is not safe, Session is safe
    • Data size: Cookie maximum 3KB, Session has no size limit
    • Storage time: Cookies can be stored for a long time through setMaxAge(), and the Session defaults to 30 minutes.
    • Server performance: Cookies do not occupy server resources, and Sessions occupy server resources.
  • in conclusion

    • Cookies are used to ensure user identification when not logged in.
    • Session is used to save data after user login

One final word

Thank you all for reading. The article is compiled through online resources and my own learning process. I hope it can help everyone.

With little talent and little knowledge, it is inevitable that there will be mistakes. If you find any mistakes, you can point them out and I will correct them.

Insert image description here

Guess you like

Origin blog.csdn.net/m0_69383623/article/details/128495153