quick start session

1. The concept of session

Server-side conversation technology, sharing data between multiple requests of a conversation again, and storing the data in a server-side object.

2. Quick start

1. Create servlet
2. Get session

object getAttribute(String value)
void setAttribute(String name,Object value)
void removeAttribute (String name)

Storing data

//1.通过request对象获取session
HttpSession session = request.getSession();
//2.给session对象设置属性和值
session.setAttribute("user","zhangsan");

Use session to fetch data

HttpSession session = request.getSession();
Object user = session.getAttribute("user");
System.out.println("session获取的user对象值时:"+user);

When you run the second one, you can get the value stored in the first session
Insert picture description here

3. The principle of session

Through the above example, we found that two servlets were created, the values ​​were stored in the session, the values ​​were stored in the session of s1, and the values ​​were obtained in the session of s2.
When a session is created for the first time, a cookie object is created in memory, and each session object has a corresponding unique session object id. When the browser visits the session, the server will correspond to a request header through the cookie, and the request header information is set-cookie: JSESSIONID=id value. Then, when the browser accesses the second servlet, it will carry the request header information, session: JSESSION=id value, and find the corresponding session according to the id name.

Insert picture description here

Guess you like

Origin blog.csdn.net/s001125/article/details/111597405