Introduction to the difference between Session and Cookie + interview questions

Session

session:

  • Corresponding English word: session
  • The user opens the browser, performs a series of actions, and then closes the browser. The whole process is called a session
  • A session contains multiple requests

The session mechanism is part of the B/S structure, and its main function is to save the session state. (After the user logs in successfully, save the user's logged-in status to the session)

The reason for using the session mechanism

  • Because the HTTP protocol is a stateless protocol
    • Stateless: When requesting, B and S are connected, and when the request ends, the connection is disconnected.
    • Can reduce the pressure on the server.
  • In order to save session state, only session can be used.
  • Reasons for not using request and application
    • The scope of the request is too small: it is destroyed after one request, and the request object is not the same when the request is made again.
    • The scope of the application is too large: one application, one browser open ~ close, and then open a browser, it is still the same application object, which does not meet the state of a session.
  • From opening to closing the browser, the session object is the same.

The realization principle of session

image description:

word description:

  1. When the browser visits the server for the first time, the server will generate an object and the corresponding sessionId, and return the sessionId to the browser
  2. After the browser gets the sessionId, it saves the sessionId in the form of a cookie
  3. When accessing the server next time, the sessionId in the browser memory is automatically sent to the server, and the server finds the corresponding session object according to the sessionId
  4. After closing the browser, the memory disappears, the cookie disappears, the sessionId disappears, and the session ends

For the first visit, a sessionId returned by the server is received in the response, which is stored in the form of a cookie=7A

 

The next time you visit again, the sessionId will be automatically sent to the server

cookie disabled

The server normally sends the sessionId to the browser, but the browser rejects it, so every time the browser accesses the server, the returned session object is brand new.

If you want to use the session mechanism when cookies are disabled:

Use the URL rewriting mechanism: http://localhost:8080/testSession;jsessionid=E62524626BE76547D7287F6B7BB73239

Such a cost is relatively large, because each time a service path is accessed, a sessionId needs to be concatenated.

Summarize

  • The session is saved on the server side and is created by the server side
    • Created method:
      • request.getSession(); // get a session object
      • request.getSession(false); // Will judge whether the current session exists, if not, the returned session object is null
  • Because of the B/S structure of the HTTP protocol, the server does not know when the browser is closed, so the session will not be destroyed. When no one operates the session object for a period of time, the session object will be destroyed. The default time is 30 minutes.
  • A session: session creation ~ session destruction
  • There are two modes of session:
    • Manual destruction: the server calls the API: invalidate();
    • Timeout destruction: no one operates the session object for a period of time

Cookie

  • In the implementation principle of session, each session object has a corresponding sessionId.
  • For example: JSESSIONID=5CB05924651451FD94F42011461CC4FB, this key-value pair data is a cookie instance.
  • As long as the browser is not closed and the user initiates a request again, the browser will automatically send the cookie in the "running memory" to the server
  • The server finds the corresponding session object according to the value of "5CB05924651451FD94F42011461CC4FB"
  • The key and value in the cookie are both strings

Save location

  • Finally saved on the browser client
  • It can also be saved in the running memory [the cookie will disappear after the browser is closed]
  • It can also be saved on a disk file [permanent storage]

effect

  • Cookies, like sessions, are used to save session state

Operating cookies in java

Create a cookie instance:

Cookie product = new Cookie("productId","1gaga3g23t32g");
Cookie user = new Cookie("name","admin");

Set the valid time of the cookie

  • Valid time > 0 The cookie is written to disk.
  • Valid time = 0 The cookie is written to the disk, overwriting the previously set cookie, which can also be understood as deleting the cookie
  • Effective time < 0 The cookie will be saved in the browser's running memory
  • If this cookie is not set, it will be saved in the browser's running memory
// 设置有效时间
product.setMaxAge(60 * 60);

Set the path associated with the cookie

Example URL: http://localhost:8080/cookie/create

The default associated path is: http://localhost:8080/cookie/*, these path browsers will automatically send cookies to the server

If the associated path is set, the setting is the main

product.setPath("/cookie");

return cookie to browser

response.addCookie(product);

The server gets the cookie

The return value is an array, when the cookie cannot be obtained, it returns null

Cookie[] cookies = req.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        String name = cookie.getName();
        String value = cookie.getValue();
        System.out.println(name+"--"+value);
    }
}

interview questions

The difference between cookie and session

1.Session definition:

The Session object is stored on the server side and is mainly used to store the attribute data and configuration data required by the user session. SessionID needs to be stored on the browser side, and the browser needs to carry this SessionID when sending an interface request.

2. Definition of Cookie:

A cookie is a small piece of text data stored on the browser side, the size of which does not exceed 4KB.

Some websites use the Session mechanism to identify the user's identity, and usually store the SessionID in the cookie. When sending a network request, the cookie will be sent to the server together in the request header.

Why do you need cookies and sessions?

Cookie and Session are two different technologies used to store and maintain state information between client and server.

A cookie is a small piece of data stored by the client and passed back and forth between the client and the server. Cookies will be stored in the browser's file system, and these data will be automatically carried when the browser sends a request.

Session is a small piece of data stored on the server side, which can be used to track the user's state. Session data is stored on and maintained by the server. When the client accesses the server, the server will determine the client's identity according to the client's request, and assign a session ID to the client. The client will carry a session ID every time it requests, and the server uses this session ID to identify the client and obtain the corresponding session data.

Describe the working principle of session in detail?

Session is a mechanism for tracking user state in a web application. When a user visits a web application, the server creates a unique session ID for that user and stores that ID in a cookie in the user's browser. The session ID is used by the server to identify the user as the user interacts with the application and to store information about the user on the server side. This information can include the user's login status, shopping cart contents, browsing history, etc. By using session, web applications can implement more advanced functions, such as user authentication, data persistence, etc.

Why is session more secure than cookie?

A cookie is a mechanism for storing data on a user's computer. Web applications can use cookies to store user information such as user IDs, preferences, and shopping cart contents. However, cookies are stored on the user's computer and can be accessed and modified on the client side, which makes cookies more vulnerable to attack and forgery, making them a security threat.

In contrast, the Session mechanism stores data on the server side and sends it to the client only when the user interacts with the web application. Users cannot access or modify Session data stored on the server, which makes Session more secure than Cookie. In addition, Web applications can use SSL/TLS encryption to protect Session data in transit, further enhancing security.

In general, although both Cookie and Session are used for user tracking in Web applications, Session is more secure because it stores data on the server side instead of on the user's computer, thereby reducing security risks.

Guess you like

Origin blog.csdn.net/weixin_45934981/article/details/130192836