Cookie&Session detailed notes

1️⃣ Cookie technology

1.1 Cookie Object

  1. Create a Cookie object to store session data
new Cookie(String name, String value)
  1. Modify cookie object
void setPath(String url)
void setMaxAge(int expiry) 
void setValue(String newValue) 
  1. Send the cookie data to the browser to save
response.addCookie(cookie);
  1. The browser visits the server with the cookie, and the server receives the cookie information
request.getCookies();

1.2 Principles of Cookie Technology

  1. The server creates a Cookie object, saves the session data, and sends the cookie data to the browser
response.addCookie(cookie); // (响应头:set-cookie: name=iacky)
  1. The browser obtains the cookie data, saves it in the browser cache, and then carries the cookie data when visiting the server next time
(请求头: cookie: name=chen)
  1. The server obtains the cookie data sent by the browser.
request.getCookies();

1.3 Cookie details.

  1. The data type of the cookie must be a string. If you want to send Chinese, you must first encrypt the Chinese URL before sending it.
  2. setPath (path): modify the effective path where the cookie is located.
  • What is a valid path?
    If the cookie is set to a valid path, then when the browser visits this valid path, the cookie data will be carried to the server.
  1. setMaxAge (integer): set the valid time of the cookie
  • Positive integer: Indicates that when the time exceeds the value of the positive integer, the cookie will be lost!! (Cookies are stored in the browser's cache directory) Unit: seconds.
  • Negative integer: means that if the browser is closed, the cookie will be lost! (cookie saves the browser memory)
  • 0: means to delete the cookie with the same name
  1. There can be multiple cookies, but browsers generally only allow 300 cookies to be stored, each site can store up to 20 cookies, and the size of each cookie is limited to 4KB

1.4 Template code

public class Cookiedemo1 extends HttpServlet {
    
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
        // 创建Cookie对象,保存会话数据
        // 如果发送中文,必须先使用URLEncoder进行加密
        String name = URLEncoder.encode("张三", "utf-8");
        Cookie c1 = new Cookie("name", name);
        Cookie c2 = new Cookie("email", "[email protected]");
        // 发送cookie
        response.addCookie(c1);
        response.addCookie(c2);
        // 浏览器下次访问获取已有的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
    
    
            for (Cookie cookie : cookies) {
    
    
                // cookie的名
                String cname = cookie.getName();
                // cookie的值
                String cvalue = cookie.getValue();
                // 解密
                cvalue = URLDecoder.decode(cvalue, "utf-8");
                System.out.println(cname + "=" + cvalue);
            }
        } else {
    
    
            System.out.println("没有cookie信息!");
        }
    }
}

1.5 Cookie case

Insert picture description here

2️⃣Session technology

Concept: Session represents a session between the server and the browser. This process is continuous or intermittent. In Servlet, session refers to an object of the HttpSession class.

2.1session data structure

In servlet/jsp, what data structure does the container use to store session-related variables? Let’s guess, first of all, it must be operated synchronously, because the session is shared between threads in a multi-threaded environment, and web servers are generally multi-threaded (in order to improve performance, pool technology is also used); secondly, this The data structure must be easy to operate, preferably the traditional key-value pair access method.

So let’s first focus on a single session object. In addition to storing its own related information, such as id, Tomcat’s session also provides programmers with an interface for storing other information (在类org.apache.catalina.session. StandardSession里):

public void setAttribute(String name, Object value, boolean notify)

Here you can trace what kind of data it uses:

protected Map attributes = new ConcurrentHashMap();

This is very clear, and had a tomcat uses ConcurrentHashMapobjects to store data, it just needs to meet two points: synchronized with ease .

So what data structure does Tomcat use to store all session objects?

  • Or ConcurrentHashMap (在管理session的org.apache.catalina.session. ManagerBase类里):
protected Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();

2.2 Session creation steps / creation time / deletion time / how to maintain:

Steps:
When the JSP page does not explicitly prohibit the session, when opening the browser to request the JSP for the first time:

  1. The server will automatically create a session for it and give it a sessionID
  2. Sent to the client's browser. When the client subsequently requests other resources in this application, it will automatically add the following to the request header:Cookie:JSESSIONID=客户端第一次拿到的session ID
  3. When the server receives a request, it will receive the session ID, find the previously created session object in memory according to the ID, and provide it to the request. This is also the basic principle of session usage.

More detailed steps reproduced:

  1. The user requests a jsp page, and the page is set with session="true";

  2. The Servlet/jsp container translates it into a servlet, and loads and executes the servlet;

  3. When the Servlet/jsp container encapsulates the HttpServletRequest object, it determines whether to bind the current session to the HttpRequest or create a new session object according to whether there is jsessionid in the cookie or url. Binding);

  4. The program operates the session on demand and accesses data;

  5. If it is a newly created session, in the result response, the container will add a Set-cookie header to remind the browser to maintain the session (or use URL rewriting to present the new link to the user).

Through the above description, readers should understand when the session was created. Here is a summary from the servlet level: When the servlet requested by the user calls the getSession method, the session will be obtained. As for whether to create a new session, it depends on whether the current request is The session has been bound. When the client adds the jsessionid identifier to the request and the servlet container finds the corresponding session object based on this identifier, it will bind this session to the request object of this request, and the client request does not contain jsessionid or the corresponding jsessionid When the session has expired, the binding of the session cannot be completed, and a new session must be created at this time. At the same time, the Set-cookie header is sent to notify the client to start maintaining a new session.


Creation time:
A common misunderstanding is that a session is created when a client accesses it. However, the truth is:

  1. When the servlet requested by the user calls the getSession method, it will get the session. Whether to create a new session depends on whether the current request is bound to the session.
  2. When the client adds the jsessionid identifier to the request and the servlet container finds the corresponding session object based on this identifier, it will bind this session to the request object of this request, and the client request does not contain jsessionid or the corresponding jsessionid When the session has expired, the binding of the session cannot be completed, and a new session must be created at this time . At the same time, the Set-cookie header is sent to notify the client to start maintaining a new session.

Delete time :

There are two situations for Session destruction: timeout and manual destruction.

  1. Session timeout: Timeout refers to the fact that the server has not received the request from the client corresponding to the session for a certain period of time, and this time exceeds the maximum session timeout set by the server.

  2. Program callHttpSession.invalidate()
    Insert picture description here

  3. The server is down or the service is stopped


How to maintain:
When the session is created for the first time, the client will bring the session identifier to the server in subsequent requests. The server program can call getSession when the session is needed, and the server can bind the corresponding session To the current request, so as to achieve the maintenance of the state. Of course, this requires the support of the client. If cookies are disabled and url rewriting is not used, the session cannot be maintained.

Rewrite the url by adding jsessionid to the url request header of each request to keep the connection

If a servlet does not call getSession between several requests (or simply requests a static page), will the session be interrupted? This will not happen, because the client will only send the legal cookie value to the server. As for what the server does with the cookie, it doesn't care, and of course it cannot. After the session is established, the client will always transmit the session identifier to the server, regardless of whether the requested page is dynamic, static, or even a picture.

2.3 Session usage steps;

HttpSession object:

  1. Create HttpSession object to save session data
session = request.getSession(); 创建或获取session对象。
  1. Modify the HttpSession object
void setMaxInactivelnterval(int interval)设置session对象的有效时间。
void invalidate()  手动销毁session对象
  1. Save session data (as domain objects)
session.setAttribute("name",Object);   保存数据
session.getAttribute("name")       获取数据
session.removeAttribute("name")    删除数据。

2.4 Template code

Insert picture description here

2.5 The principle of session

  • Question: How does the server distinguish between different browser sessions?
  • Prerequisite: The data that can be retrieved from the session object must be the session object that stores the data!!!

Can you find the session results when you open the same page in the same browser and open the same page in different browsers as follows:

  1. Browser 1-Window 1 (001):
//1 创建HttpSession对象
HttpSession session = request.getSession()
//2 保存会话数据。
session.setAttribute("name"," jacky");
  1. Browser 1-Window 2 (001): available
//1 创建HttpSession对象
HttpSession session = request.getSession()
//2 保存会话数据。
session.setAttribute("name"," jacky");
  1. Browser 2: Not available
//1 创建HttpSession对象
HttpSession session = request.getSession()
//2 保存会话数据。
session.setAttribute("name"," jacky");
  1. New browser 1 (unmarked or not 001): not available
//1 创建HttpSession对象
HttpSession session = request.getSession()
//2 保存会话数据。
session.setAttribute("name"," jacky");

2.6 session details

  1. setMaxinactivelnterval (seconds): Set the effective time of the session object,
  • Question: Where is the session destroyed?
  • Note: The session object will be destroyed if the browser is not closed!!!
  • Default: Wait for 30 minutes of idle time before the session object will be destroyed.
<!--设置全局的session对象的过期时间(分钟)-->
<session-config>
	<session-timeout>1</session-timeout>
</session-config>
  1. JSESSIONID will not disappear when the browser is closed
/*设置JSESSIONID的时间,不会随着浏览器关闭而丢失!*/ 
Cookie c = new Cookie ("JSESSIONTD",session.getId());
c.setMaxAge (1*30*24*60*60) ;  //1个月
response.addCookie(c); 
  1. Directly manually destroy the sessino object v
invalidate( ); 
  1. Create or get session object
创建或得到session对象,查询session对象
request.getSession() / request.getSession(true)
如果没有sessino对象,则创建新的session对象
request.getSession(false)
得到session对象,查询session对象,如果没有session对象,直接返回null

2.7 session principle

This line of code includes the following six steps

 HttpSession session = request.getSession();
  • The server creates a Session object, and the server assigns a unique tag JSESSIONID to the session object
  • Send the JSESSIONID as a cookie to the browser
  • The browser gets the JSESSIONID and saves it, and carries this JSESSIONID to access the server during the next visit
  • The server gets the JSESSIONID, and searches for the session object with the specified JSSESSINOID in the server memory
    • If found, return this session object
    • If it is not found, it may return null directly, or create a new session object.

3️⃣The similarities and differences between Cookie and Session

Both cookie and session belong to sub-packages under the servlet package

3.1 Features

Cookie features:

  1. Session data is placed on the browser side
  2. The data type can only be string, and there is a size limit, which is relatively unsafe for data storage

Session features:

  1. Session data is placed on the server side (server memory), occupying server resources
  2. Any data type, no size limit
  3. Relatively safe

3.2 Storage location

cookie: browser
Insert picture description here
session: server
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_40597409/article/details/113685337