Cookies and Sessions

Table of Contents

1. What are cookies?

2. What is Session?

2.1 Session usage process

3. The difference between Cookie and Session

4. Core methods

4.1 Session methods in HttpServlet

4.2 Methods in the HttpSession class

4.3 Methods in Cookie class

1. What is Cookie?

Cookies are a mechanism for browsers to store data locally

  • Cookies come from the server. The server will have a Set-Cookie field in the response. Through this field, the data that needs to be saved locally can be returned through the server.
  • When the browser subsequently accesses the server, all current local cookies will be brought there through http requests.
  • Use cookies to save the current user’s login status

Save the user’s identity in the cookie, how to assign the identity at this time, and how to store the identity information specifically. This is what the Session mechanism does.

2. What is Session?

The server receives many requests at the same time. The server needs to clearly distinguish which user each request belongs to, and the corresponding relationship between each user token and user information needs to be recorded in the server.

The essence of a session 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 (user information can be flexibly designed according to needs)

sessionId is a “unique string” generated by the server. From the perspective of the session mechanism, this unique string is called “sessionId“. But looking at the entire login process, this unique string can also be called “token“. sessionId and token can be understood as different names for the same thing (called from different perspectives)

2.1 Session usage process

  1. When the user logs in, the server adds a new record to the Session and returns the sessionId/token to the client. (e.g. returned via the Set-Cookie field in the HTTP response).
  2. When the client sends a request to the server later, it needs to bring the sessionId/token in the request. (e.g. via the Cookie field in the HTTP request).
  3. After the server receives the request, it obtains the corresponding user information from the Session information based on the sessionId/token in the request, and then performs subsequent operations.

The Servlet Session is saved in memory by default. If you restart the server, the session data will be lost

  • Cookie is a client-side mechanism, and Session is a server-side mechanism.
  • Cookie and Session 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. This data is not necessarily user identity information, nor is it necessarily token/sessionId
  • The token/sessionId in Session is not necessarily passed through Cookie/Set-Cookie.

Four. Core Methods

4.1 Methods about Session in HttpServlet

Related methods in the HttpServletRequest class

Method Description
HttpSession
getSession()
Get the session in the server. If the parameter is true, a new session will be created when no session exists; if the parameter is
Is false, returns null when no session exists
Cookie[]
getCookies()
Returns an array containing all Cookie objects sent by the client for this request. will automatically
The format in the cookie is parsed into key-value pairs
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws Servlet
        //Use HttpServletRequest in the servlet to obtain the Session object
        // If the parameter is true, the Session object will be actively created when there is no Session object; if false, it will not be created.
        HttpSession session = req.getSession(true);
        //Use the created session object to store user information
        session.setAttribute("user",user);
    }

Related methods in the HttpServletResponse class

Method Description
void addCookie(Cookie cookie) Specify Cookies are added to the response

4.2 Methods in the HttpSession class

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

Method Description
Object getAttribute(String
name)
This method returns the object with the specified name in this session. If there is no
If there is an object with the specified name, null is returned.
void setAttribute(String
name, Object value)
This method binds an object to the session using the specified name
boolean isNew() Determine whether the current session is a newly created session
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws Servlet
        //Use HttpServletRequest in the servlet to obtain the Session object
        // If the parameter is true, the Session object will be actively created when there is no Session object; if false, it will not be created.
        HttpSession session = req.getSession(true);
        //Use the created session object to store user information, where user is the entity class
        session.setAttribute("user",user);
        // Get user information
        session.getAttribute("user");
    }

Each Cookie object is a key-value pair

Method Description
String getName() This method returns cookie The name. The name cannot be changed after creation. (This value is set by the Set-Cooke field to the browser)
String getValue() This method obtains the value associated with the cookie
void setValue(String
newValue)
This method sets the value associated with the cookie
  • What is stored in the HTTP Cooke field is actually multiple sets of key-value pairs. Each key-value pair corresponds to a Cookie object in the Servlet.
  • Obtain a series of Cookie key-value pairs in the request through HttpServletRequest.getCookies()
  • New Cookie key-value pairs can be added to the response via HttpServletResponse.addCookie()