JavaWeb_Session Technology

Overview of Session Tracking Technologies

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. Multiple requests and responses can be included in one session.

  • After the browser sends a request to the server responds 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 the server can continue to use the session to send and respond to requests. The above-mentioned whole process is called session session
    tracking: a method of maintaining the state of the browser. The server needs to identify whether multiple requests come from the same browser in order to share data between multiple requests in the same session.
  • The server will receive multiple requests, which may come from multiple browsers
  • The server needs to identify whether the request is from the same browser
  • The process used by the server to identify the browser, this process is session tracking
  • After the server recognizes the browser, it can share data between multiple requests in the same session
    Client-side session tracking technology: Cookie
    Server-side session tracking technology: Session

Cookie

concept

Cookie: Client-side session technology, which saves data to the client, and every subsequent request carries Cookie data for access.

Cookie workflow

  • The server provides two Servlets, namely ServletA and ServletB
  • The browser sends HTTP request 1 to the server, and the server ServletA receives the request and performs business processing
  • The server ServletA can create a Cookie object and store the data of name=zs into the Cookie during processing
  • When the server ServletA responds to the data, it will respond the Cookie object to the browser
  • When the browser receives the response data, it will store the data in the Cookie object in the browser memory. At this time, the browser and the server will establish a session
  • In the same session, the browser sends HTTP request 2 to the server ServletB again, and the browser will carry all the data in the Cookie object
  • After ServletB receives the request and data, it can obtain the data stored in the Cookie object, so that data sharing can be realized between multiple requests in the same session

Basic use of cookies

send cookies

Create a Cookie object and set the data

Cookie cookie = new Cookie("key","value");

Send Cookie to the client: use the response object

response.addCookie(cookie);

get cookie

Get all the cookies carried by the client, using the request object

Cookie[] cookies = request.getCookies();

Traverse the array and get each Cookie object: for
use the Cookie object method to get data

cookie.getName();
cookie.getValue();

Cookie principle analysis

Two request header information in the HTTP protocol:

  • Response header: set-cookie
  • Request header: cookie
  • AServlet sends Cookie to the front end, and BServlet obtains the function of Cookie from request
  • When AServlet responds to data, the Tomcat server responds to data based on the HTTP protocol
  • When Tomcat finds that the backend is to return a Cookie object, Tomcat will add a line of Set-Cookie:username=zs to the response header
  • After the browser gets the response result, it can get the Set-Cookie corresponding value username=zs from the response header, and store the data in the browser's memory
  • When the browser sends the request to BServlet again, the browser will automatically add Cookie in the request header: username=zs and send it to the server BServlet
  • The Request object will encapsulate the value corresponding to the cookie in the request header into each Cookie object, and finally form an array
  • After the BServlet obtains the Cookie[] through the Request object, it can obtain the data it needs

Cookie usage details

Cookie lifetime

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

  • Set the cookie lifetime
setMaxAge(int seconds)

The parameter values ​​are:
1. Positive number: Write the cookie to the hard disk of the computer where the browser is located for persistent storage. When the time expires, the cookie will be automatically deleted (unit: second)
2. Negative number: default value, the cookie is in the current browser memory, when the browser is closed, the cookie will be destroyed
3. Zero: delete the corresponding cookie

Cookie storage Chinese

1. URL-encode Chinese in AServlet, use URLEncoder.encode(), and store the encoded value in Cookie
2. Obtain the value in Cookie in BServlet, and 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

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);
//获取数据
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;

Session

Basic use of Session

concept

Session: server session tracking technology: save data to the server

  • Session is stored on the server and Cookie is stored on the client
  • The data stored on the client is easy to be stolen and intercepted, and there are many insecure factors
  • Data stored on the server side is more secure than on the client side

work process

  • The AServlet on the server side gets a Session object and stores the data in it
  • The BServlet on the server side gets the same Session object and fetches data from it
  • Data sharing between multiple requests in one session can be realized

Basic use of Session

Get the Session object, using the request object

HttpSession session = request.getSession();

The functions provided by the Session object:

  • Store data in the session domain
void setAttribute(String name, Object o)
  • According to the key, get the value
Object getAttribute(String name)
  • According to the key, delete the key-value pair
void removeAttribute(String name)

Principle Analysis of Session

Session是基于Cookie实现的
(1)demo1在第一次获取session对象的时候,session对象会有一个唯一的标识,假如是id:10
(2)demo1在session中存入其他数据并处理完成所有业务后,需要通过Tomcat服务器响应结果给浏览器
(3)Tomcat服务器发现业务处理中使用了session对象,就会把session的唯一标识id:10当做一个cookie,添加Set-Cookie:JESSIONID=10到响应头中,并响应给浏览器
(4)浏览器接收到响应结果后,会把响应头中的coookie数据存储到浏览器的内存中
(5)浏览器在同一会话中访问demo2的时候,会把cookie中的数据按照cookie: JESSIONID=10的格式添加到请求头中并发送给服务器Tomcat
(6)demo2获取到请求后,从请求头中就读取cookie中的JSESSIONID值为10,然后就会到服务器内存中寻找id:10的session对象,如果找到了,就直接返回该对象,如果没有则新创建一个session对象
(7)关闭打开浏览器后,因为浏览器的cookie已被销毁,所以就没有JESSIONID的数据,服务端获取到的session就是一个全新的session对象

Session usage details

Passivation and activation of Session

Passivation: After the server shuts down normally, Tomcat will automatically write the Session data into the file on the hard disk.
Activation: After restarting the server, load the data from the file to the Session, and the SESSIONS.ser file in the path will be deleted
(passivation and activation of the session are automatically completed by the server)

The session data is stored on the server side, and the session data will be saved when the server is restarted, but after the browser restarts, it is equivalent to establishing a new session, and obtaining the session data is a new object. Therefore, the session cannot save data for a long time, and the cookie is stored on the client side, which can be saved for a long
time

Session destruction

By default, it will be destroyed 30 minutes after no operation (you can configure the destruction time in web.xml)
and call invalidate() of the Session object to destroy

// 获取Session对象
HttpSession session = request.getSession();
System.out.println(session);
// 销毁
session.invalidate();

Differences and Application Scenarios 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 unlimited size
    • Storage time: Cookies can be stored for a long time through setMaxAge(), and Session defaults to 30 minutes
    • Server performance: Cookies do not occupy server resources, while Sessions occupy server resources
  • Application scenario:
    • Shopping cart: use cookies to store
    • Displayed in the name of the logged-in user: use Session to store
    • Remember me function: use cookies to store
    • Verification code: use session to store
  • in conclusion
    • Cookies are used to ensure user identification without logging in
    • Session is used to save data after user login

Guess you like

Origin blog.csdn.net/qq_57689612/article/details/129135477