【web】Understanding Cookie and Session Mechanism

Hits: 0

🤞Catalog 🤞

💖 1. Understanding Cookies

💖 2. Understand the session mechanism (Session)

💖 3. Core Methods

3.1 Related methods in the HttpServletRequest class

3.2 Related methods in the HttpServletResponse class

3.3 Related methods in the HttpSession class

3.4 Related methods in the Cookie class

💖 4. Difference between Cookie and Session

4.1 Store only cookies

4.2 Only take cookies

[Hello everyone, I am an ape who loves to cook. If you like this article, give it a like 👍 and pay attention. I will continue to share the daily question and a summary of other important knowledge points of [SSM in the future] ]

Previous article: “[SSM] First Understanding of Spring & Accessing Bean Objects”

🎫1. Understanding Cookies

The HTTP protocol itself is a ” stateless ” protocol

The meaning of “stateless” means: by default, the communication between the client and the server of the HTTP protocol has no direct connection with the next peer.

But in actual development, we often need to know the relationship between requests and requests. For example, after logging in to a website, the server can know whether you have logged in when you visit again.

The “token” in the figure is stored in the Cookie field, and the “token” is similar to a VIP card or pass. After you have this token, you can conduct subsequent visits.

A cookie is actually a small piece of textual information. The client requests the server, and if the server needs to record the user status, it uses the response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the website again, the browser submits the requested URL to the server together with the cookie. The server checks the cookie to identify user status. The server can also modify the content of the cookie as needed.

At this time, the server needs to record the token information and the user information corresponding to the token. This is the work done by the [Session mechanism.]

🎫2. Understand the session mechanism (Session)

The server may receive many requests at the same time. To distinguish the user of each request, the server needs to record the token and user information of each user on the server.

The essence of all sessions is a ” hash table “, which stores some key-value pair structures. The key is the ID of the token (token/sessionId), and the value is the user information.

sessionId and token can be understood as different names of the same thing (different perspectives) 

  • When the user logs in, the server adds a new record to the Session and returns the sessionId / token to the client. (For example, through the Set-Cookie field in the HTTP response).
  • When the client sends a request to the server later, it needs to bring the sessionId/token in the request. (For example, through the Cookie field in the HTTP request).
  • After the server receives the request, it obtains the corresponding user information in the session information according to the sessionId / token in the request, and then performs subsequent operations.

Note: The session of the servlet is stored in the memory , and the session data will disappear after restarting the server, which is equivalent to restarting a process. 

🎫3. Core method

3.1 Related methods in the HttpServletRequest class

3.2 Related methods in the HttpServletResponse class

3.3 Related methods in the HttpSession class

An HttpSession object contains multiple key-value pairs. We can store any information we need in the HttpSession.

3.4 Related methods in the Cookie class

Each Cookie object is a key-value pair . 

  • What is stored in the Cookie field of HTTP is actually multiple sets of key-value pairs. Each key-value pair corresponds to a Cookie object in the Servlet
  • Get a series of cookie key-value pairs in the request through HttpServletRequest.getCookies()
  • A new Cookie key-value pair can be added to the response via HttpServletResponse.addCookie() 

a. First visit

@WebServlet ( "/first-visit" )
 public  class  FirstVisitServlet  extends  HttpServlet  {
     @Override 
    protected  void  doGet (HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
         // // false will not add a new cabinet, true will add a new cabinet 
        HttpSession session = req.getSession( true );
         // record 
        session.setAttribute( "Date" , new Date());

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("txt/plain");
        resp.getWriter().print( "Successful membership process!" );
    }
}

b. After the first visit, you can make a request with a cookie after getting a cookie

@WebServlet("/get-time")
public class GetCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("txt/plain");
        PrintWriter writer = resp.getWriter();

        // false will not add a new cabinet, true will add a new cabinet 
        HttpSession session = req.getSession( false );
         if (session == null ){
            writer.println( "No cabinet" );
             return ;
        }
        Object o = session.getAttribute("Date");
        if(o == null){
            writer.println( "There is a locker but the member information is empty" );
             return ;
        }
        Date date = (Date) o;
        writer.println( "There is a member, the member information is: " + date);
    }
}

🎫4. Difference between Cookie and Session

  • Cookie is a client-side mechanism , and Session is a server-side mechanism .
  • Cookies and Sessions are often used together. But they do not have to be used together.

It is completely possible to use cookies to save some data on the client side. These data are not necessarily user identity information, nor are they necessarily token / sessionId

The token/sessionId in Session does not have to be passed through Cookie/Set-Cookie.

4.1 Store only cookies

@WebServlet("/only-set-cookie")
public class OnlySetCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie1 = new Cookie( "name" , "xiao" );
 // Cookie other attributes 
// cookie1.setMaxAge(60); // Set expiration time 
// cookie1.setComment(); // Set cookie comment 
// cookie1 .setDomain(); // Set the supported domain name to increase the range of the supported root domain name 
// cookie1.setPath(); // Set the supported path to narrow the range, generally the default is "/", and the root directory is all With Cookie 
// // Other
        resp.addCookie(cookie1);

        Cookie cookie2 = new Cookie("gender","male");
        resp.addCookie(cookie2);
    }
}

4.2 Only take cookies

@WebServlet("/only-get-cookie")
public class OnlyGetCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() +" => "+cookie.getValue());
        }
    }
}

This sharing is here. If you like this article, please like and follow , or if you have any confusion about the article, you can privately message me.

🏓🏓🏓

You may also like...

Leave a Reply

Your email address will not be published.