What is conversation?
The browser starts from requesting access to the server until accessing the browser ends and the browser closes. During this period, all requests and responses generated between the browser and the server are added together, which is called a session between the browser and the server. Some data is often generated in a session, and these data need to be saved, for example: *For example, when you do not log in, recording the goods in the shopping cart is actually storing the goods information in coocie or session.
You can save the data generated in the session with a cookie or session
How cookies work
1: Cookie is to save the data generated in the session on the client, which belongs to the client technology;
2: Cookies work based on two headers: set cookie response header and cookie request header;
3: Send cookies from the server to the browser through the set cookie response header, and let the browser save them internally; Once the browser saves the cookie, every time the browser accesses the server in the future, it will bring the cookie information back to the server through the cookie request header. When necessary, the server can obtain the cookie data in the request, so as to realize some functions;
Application of API in cookie
1. Create cookie object
Cookie cookie = new Cookie（String name，Stringvalue）； //When creating a cookie, you need to specify the name of the cookie and the value to be saved //Once the cookie name is specified, it cannot be modified!
2. Add the cookie to the response
response.addCookie(Cookie cookie); //Add the cookie to the response. The server is responsible for sending the cookie information to the browser, and then the browser saves it internally (you can call this method multiple times to add more than one cookie)
3. Get the array composed of all cookie objects in the request
Cookie cookie = request.getCookies(); //Get the cookie object array composed of all cookies carried in the request. If the request does not carry any cookies, calling this method will return null.
4. Delete cookies in the browser
//The cookie API does not provide a method to delete cookies directly. Cookies can be deleted indirectly by other means //Delete the cookie named Cart: you can send another cookie with the same name to the browser (that is, the name is also called cart), and set the maximum lifetime of the cookie to zero. Because the browser distinguishes cookies according to the name of the cookie, if you send cookies with the same name to the browser twice, the later sent cookie will overwrite the previously sent cookie. The cookie sent later has a lifetime of zero, so the browser will delete it immediately after receiving it!
5. Common methods of cookies:
cookie.getName(); // Gets the name of the cookie cookie.getValue(); // Gets the value saved in the cookie cookie.setValue(); // Set / modify the value saved in the cookie (there is no setname method because the cookie name cannot be modified) cookie.setMaxAge(); // Set the maximum lifetime of cookies (if not set, cookies will be destroyed at the end of a session by default!)
6. Set the maximum cookie lifetime (setmaxage):
cookie。 Setmaxage (60) // unit: seconds
Session principle and Application
How session works
1: Session is to save the data generated in the session on the server side, which belongs to the server-side technology;
2: Session is a domain object. A map set is also saved in session. Saving data to session is actually saving data to the specified map set of session;
3: Through the session. SetAttribute () method, data can be stored in the session, and through the session. Getattribute () method, data can be taken out of the session;
Session is a domain object
Get session object:
request.getSession() //Get a session object. If there is a session corresponding to the current browser in the server, the session object will be returned directly; If there is no corresponding session, a new session object will be created first and then returned;
Session is a domain object. A map set is also saved in the session, and the sessions also provides methods to access data, as follows:
session.setAttribute(String attrName,Object attrValue); //Add a domain attribute to the session domain. The attribute name must be of string type, and the attribute value can be of any type session。setAttribute(String attrName); //The attribute value in the field can be obtained according to the attribute name, and the return value is an object type
Three characteristics of session domain objects:
(1) Life cycle:
The first time the request. Getsession () method is called, a session object is created（ When the browser has no corresponding session on the server side, call the request. Getsession () method, and the server will create a session object)
1. Overtime destruction：
By default, when the session is not accessed for more than 30 minutes, the session will be destroyed over time (30 minutes is the default time and can be modified);
When the invalidate method of a session is called, the session will be destroyed immediately;
3. Accidental death:
1) When the server shuts down abnormally (the server shuts down abnormally due to hardware damage, power failure, memory overflow, etc.), the session will be destroyed with the server shutting down;
2) When the server shuts down normally, before shutting down, the server will serialize and save the internal session object to the work directory of the server and turn it into a file. This process is called session passivation (serialization); Start the server again, and the passivated session will return to the server again and become an object in the service. This process is called session activation (deserialization);
(2) Scope of action:
Within the scope of one session (the same session object is obtained)
(3) Main functions:
Share data throughout the session
summaryThe difference between the two
Both cookie and session belong to session technology and can save the data generated in the session. However, due to the different working principles and characteristics of cookie and session, their application scenarios are also different.
1. Cookie is to store the data generated in the session intoBrowser client, belonging to client technology (JS can access cookies)
2. Cookies are used to save data to the browser client. It is easy to lose or steal cookies with the user’s operation. Therefore, the data stored in cookies is not stable and safe
3. The data in the cookie is stored in the browser, which has little impact on the server and can save the data for a long time
4. The browser has restrictions on the size and number of cookies. Generally, each site sends no more than 20 cookies to the browser, and the size of each cookie is no more than 1KB
Summary: cookies are suitable for storing data that needs to be saved for a long time and does not require high security;
1. Session is a server-side technology that stores the content generated by the session to the server
2. Session stores data into the session object on the server side, which is relatively more secure and stable. It is not easy to cause data loss in the session with the user’s operation
3. Session is an object on the server side. When the concurrency is high, each browser client must correspond to a session object on the server side, which occupies the memory space of the server and affects the efficiency
Summary: session is suitable for storing data that requires high security but does not need to be saved for a long time;
Note: the problem of saving Chinese data in cookies has been solved in Tomcat 8.5 and later versions!
Note: the previous session cannot be obtained
After saving the goods into the session, close the browser and then open the browser to access the server. At this time, the previous session cannot be obtained. Because session works based on cookies.
After the server creates a session, it will assign a unique number to the session, called the session ID. in this response, the server will send the session ID to the browser with a cookie named jsessionid and save it inside the browser.
Since the cookie that saves the sessionid is a session level cookie by default, the cookie will be destroyed and the sessionid will be lost after the browser is closed. Therefore, the next time you access the server, you cannot get the previous session without the session ID. The product information in the session cannot be obtained
Solution: we can create a cookie named jsessionid, save the session ID, and set the maximum lifetime of the cookie to save the cookie to the hard disk (even if the browser is closed, the cookie will not be destroyed). In this way, we can bring the sessionid to the server the next time we visit the server, and the server can obtain the previous session through the sessionid. Get product information from session