Specifically speaking, the cookie mechanism uses a solution that maintains state on the client side, while the session mechanism uses a solution that maintains state on the server side.
At the same time, we also see that since the solution of maintaining state on the server side also needs to save an identity on the client side, the session mechanism may need to use the cookie mechanism to achieve the purpose of saving the identity, but in fact there are other options.
2. The difference between session cookies and persistent cookies
If the expiration time is not set, it means that the life cycle of this cookie is during the browser session. As long as the browser window is closed, the cookie will disappear. Such cookies that last for the duration of the browsing session are called session cookies. Session cookies are generally not stored on the hard disk but in memory.
If an expiration time is set, the browser will save the cookies to the hard disk. After closing and opening the browser again, these cookies will still be valid until the set expiration time is exceeded.
Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. Different browsers have different ways of handling cookies stored in memory.
3. How to use automatic login
When a user registers on a website, he or she will receive a cookie with a unique user ID. When the client later reconnects, this user ID is automatically returned and the server checks it to determine if it is a registered user with automatic login selected, allowing the user to access resources on the server without giving an explicit username and password. .
4. How to customize the site according to the user’s preferences
The website can use cookies to record the user’s wishes. For simple settings, the website can directly store the page settings in cookies to complete customization. However, for more complex customizations, the website only needs to send a unique identifier to the user, and the server-side database stores the page settings corresponding to each identifier.
5. Sending cookies
1. Create a Cookie object
2. Set the maximum time limit
3. Put the cookie into the HTTP response header
If you create a cookie and add it Sent to the browser, it is a session-level cookie by default: it is stored in the browser's memory and is deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to use maxAge and give a time in seconds. Setting the maximum age to 0 instructs the browser to delete the cookie.
To send cookies, you need to use the addCookie method of HttpServletResponse to insert the cookie into a Set-Cookie HTTP request header. Since this method does not modify any previously specified Set-Cookie header, but creates a new header, we call this method addCookie instead of setCookie. Also remember that response headers must be set before any document content is sent to the client.
6. Cookie Reading
1. Call request.getCookie
To obtain the cookies sent by the browser, you need to call the getCookies method of HttpServletRequest. This call returns an array of Cookie objects, corresponding to the HTTP request The value entered in the Cookie header.
2. Loop through the array and call the getName method of each cookie until the cookie of interest is found
Cookies are related to your host (domain), not your servlet or JSP page. Therefore, although your servlet may only send a single cookie, you may also get many unrelated cookies.
For example:
String cookieName = “userID”;
Cookie cookies[] = request.getCookies();
if (cookies!=null){
for(int i=0; i
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())){
doSomethingWith(cookie.getValue());
}
}
}
7. How to use cookies to detect first-time visitors
A. Call HttpServletRequest.getCookies() to obtain the Cookie array
B. Retrieve in a loop whether the cookie with the specified name exists and whether the corresponding value is correct
C. If so, exit the loop and set the distinction identifier
D. Determine whether the user is a first-time visitor based on the distinction identifier and perform different operations
8. Common mistakes in using cookies to detect first-time visitors
It cannot be assumed that the user is a first-time visitor just because a specific data item does not exist in the cookie array. If the cookie array is null, the customer may be a first-time visitor, or it may be caused by the user deleting or disabling cookies.
However, if the array is non-null, it only shows that the customer has visited your website or domain, and it does not mean that they have visited your servlet. Other servlets, JSP pages and non-Java web applications can set cookies. Depending on the path settings, any cookie may be returned to the user's browser.
The correct approach is to determine whether the cookie array is empty and whether the specified Cookie object exists and the value is correct
9. Use cookies. Notes on Attributes
Attributes are part of the header sent from the server to the browser; but they are not part of the header returned by the browser to the server.
Therefore, in addition to the name and value, the cookie attributes only apply to the browser. The cookie output by the server to the client; the cookie from the server side does not set these attributes.
Therefore, do not expect to use this attribute in cookies obtained through request.getCookies. This means that you can't implement changing cookie values just by setting the maximum age of the cookie, emitting it, looking for the appropriate cookie in the subsequent input array, reading its value, modifying it and saving it back to the cookie. .
10. How to use cookies to record the visit count of each user
1. Get the value of the cookie in the cookie array that is specifically used to count the number of user visits
2. Convert the value into int type
3. Add 1 to the value and re-create a Cookie object with the original name
4. Reset the maximum time limit
5. Output the new cookie
11. The different meanings of session in different environments
session , often translated as conversation in Chinese, its original meaning refers to a series of actions/messages that have a beginning and an end. For example, making a phone call is a series of processes from picking up the phone to dialing to hanging up the phone, which can be called a session.
However, when the word session is associated with a network protocol, it often implies two meanings: "connection-oriented" and/or "maintaining state".
The semantics of session in the Web development environment have been expanded. Its meaning refers to a type of solution used to maintain state between the client and the server. Sometimes Session is also used to refer to the storage structure of this solution.
12. Session mechanism
The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to save information.
But when the program needs to create a session for a client's request, the server first checks whether the client's request contains a session identifier - called session id. If it already contains a session id, it means that this has been done before. If the client has created a session, the server will retrieve the session and use it according to the session ID (if it cannot be retrieved, it may create a new one. This may occur when the server has deleted the session object corresponding to the user, but the user artificially A JSESSION parameter is appended to the requested URL).
If the client request does not include a session id, a session will be created for this client and a session id associated with this session will be generated. This session id will be returned to the client for storage in this response.
13. Several ways to save session id
A. The session ID can be saved using cookies, so that during the interaction the browser can automatically send this ID to the server according to the rules.
B. Since cookies can be artificially disabled, there must be other mechanisms to still pass the session id back to the server when the cookie is disabled. A commonly used technique is called URL rewriting, which is to append the session id to the end of the URL path. There are two ways of appending, one is as additional information to the URL path, and the other is as a query string appended to the end of the URL. The network maintains state throughout the entire interaction, and this session id must be included at the end of every path that the client may request.
C. Another technique is called form hidden fields. That is, the server will automatically modify the form and add a hidden field so that the session id can be passed back to the server when the form is submitted.
14. When is the session created?
A common mistake is to think that the session is created when a client accesses it. However, the fact is that it is not until a server-side program (such as Servlet) calls HttpServletRequest.getSession(true) Such statements will only be created.
15. When is the session deleted?
The session is deleted under the following circumstances:
A. The program calls HttpSession.invalidate()
B. The time interval since the last session id sent by the client exceeds the maximum validity time of the session
C. The server process is stopped
Note again that closing the browser will only invalidate the session cookie stored in the memory of the client browser, but will not invalidate the session object on the server side.
16. What are the disadvantages of URL rewriting
Use URL rewriting for all URLs, including hyperlinks, form actions, and redirected URLs. Each URL that refers to your site, as well as those that are returned to the user (even through indirect means, such as the Location field in a server redirect), adds additional information.
This means that there cannot be any static HTML pages on your site (at least there cannot be any links in the static pages to the dynamic pages of the site). Therefore, each page must be generated dynamically using servlets or JSP. Even if all pages are generated dynamically, if the user leaves the session and comes back again via bookmarks or links, the session information will be lost because the stored link contains incorrect identification information - the SESSION ID behind the URL has expired.
17. What are the disadvantages of using hidden form fields
This method can only be used when each page is dynamically generated by form submission. Clicking on a regular hypertext link does not generate a form submission, so hidden form fields cannot support usual session tracking and can only be used in a series of specific operations, such as the checkout process of an online store
18. Session tracking Basic steps
1. Access the session object related to the current request
2. Find session-related information
3. Storing session information
4. Discard session data
19. The difference between getSession()/getSession(true) and getSession(false)
getSession()/getSession(true): Return the session when the session exists, otherwise create a new session and return This object
getSession(false): Returns the session when the session exists, otherwise the session will not be created and null
20. How to associate information with the session
setAttribute will replace any previously set value; if you want to remove a value without providing any replacement, you should use removeAttribute. This method will trigger the valueUnbound method of all values that implement the HttpSessionBindingListener interface.
21. Are there any restrictions on the type of session attributes?
Usually the type of session attributes only needs to be Object. Except null or basic types, such as int, double, boolean.
If you want to use a basic type value as an attribute, you must convert it into the corresponding encapsulated class object
22. How to discard session data
A. Only remove the data created by the servlet you wrote:
Call removeAttribute("key") to discard the value associated with the specified key
B. Delete the entire session (in the current web application):
Call invalidate to discard the entire session. Doing so will lose all session data for that user, not just the session data created by our servlet or JSP page
C. Logout the user from the system and delete all sessions belonging to him (or her)
Call logOut to logout the client from the web server and discard all sessions associated with the user (at most one per web application). This operation may affect multiple different web applications on the server.
23. The wrong way to use isNew to determine whether the user is a new or old user
public boolean isNew() method If the session has not yet had any contact with the client program (browser), this method returns true, which is generally This is because the session is new and not caused by an incoming client request.
But if isNew returns false, it just means that they have visited the web application before, and it does not mean that they have visited our servlet or JSP page.
Because the session is related to the user, a session may have been created on every page the user visited before. Therefore, if isNew is false, it can only mean that the user has visited the web application before. The session can be created by the current page or by a page that the user has visited before.
The correct approach is to determine whether a specific key exists in a session and whether its value is correct
24. What is the difference between Cookie expiration and Session timeout
The session timeout is determined by the server Maintenance, which is different from the cookie expiration date. First, sessions are generally based on memory-resident cookies, which are not persistent cookies and therefore do not have an expiration date. Even if the JSESSIONID cookie is intercepted and an expiration date is set for it, it is sent. Browser sessions and server sessions can also be very different.
25. Are the life cycles of session cookie and session object the same?
When the user closes the browser, although the session cookie has disappeared, the session object is still saved on the server side
26. Whether As long as the browser is closed, the session will disappear
The program usually sends an instruction to delete the session when the user logs off. However, the browser never actively notifies the server that it will be closed before closing, so the server simply does not There will be no chance of knowing that the browser has been closed. The server retains this session object until it is inactive for a set interval.
The reason for this misunderstanding is that most session mechanisms use session cookies to save the session id. After closing the browser, the session id disappears, and the original session id cannot be found when connecting to the server again. session.
If the cookie set by the server is saved to the hard disk, or some method is used to rewrite the HTTP request header sent by the browser and send the original session ID to the server, the original session can still be found when the browser is opened again.
Precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. When the time since the client last used the session exceeds this expiration time, the server can consider that the client has stopped. When the activity is active, the session will be deleted to save storage space.
From this we can draw the following conclusions:
When closing the browser, only the session cookie in the memory of the browser will disappear, but it will not cause the session object saved on the server to disappear, nor will it make it disappear. Persistent cookies saved to the hard drive disappear.
27. Will opening two browser windows use the same session or different sessions to access the application?
Usually session cookies cannot be used across windows. When you open a new browser window and enter the same page , the system will give you a new session id, so that the purpose of our information sharing will not be achieved.
At this time, we can first save the session id in the persistent cookie (by setting the maximum validity time of the session), and then read it out in a new window to get the session id of the previous window. In this way, through the session cookie and persistent cookie Combined, we can achieve cross-window session tracking.
28. How to use session to display the number of visits of each customer
Since the number of visits of a customer is an integer variable, basic type variables such as int, double, and boolean cannot be used in the attribute type of session. , so we need to use these basic types of encapsulated type objects as the values of attributes in the session object
But like Integer, it is an unmodifiable (Immutable) data structure: it cannot be changed after it is constructed. This means that each request must create a new Integer object and then use setAttribute to replace the value of the old attribute that existed before. For example:
HttpSession session = request.getSession();
SomeImmutableClass value = (SomeImmutableClass)session.getAttribute(“SomeIdentifier”);
if (value= =null){
value = new SomeImmutableClass (…); // Create a new immutable object
}else{
value = new SomeImmutableClass(calculatedFrom(value)); // Create a new object after recalculating the value
}
session.setAttribute(“someIdentifier”,value); // Use the newly created object to overwrite the original old object
29. How to use sessions to accumulate user data
Use variable data structures, such as arrays , List, Map, or application-specific data structure with writable fields. This way, there is no need to call setAttribute unless the object is allocated for the first time. For example
HttpSession session = request.getSession();
SomeMutableClass value = (SomeMutableClass)session.getAttribute("someIdentifier");
if(value == null){
value = new SomeMutableClass( …);
session.setAttribute(“someIdentifier”,value);
}else{
value.updateInternalAttribute(…); // If the object already exists, update its attributes without resetting the attributes.
}
30. Different processing of immutable objects and modifiable objects when updating session data
Immutable objects cannot be changed once they are created, so the values of attributes in the session must be modified every time Sometimes, you need to call setAttribute("someIdentifier", newValue) to replace the original attribute value, otherwise the attribute value will not be updated. Since the changeable object itself generally provides a method to modify its own attributes, it must be modified every time. When changing the value of an attribute in a session, you only need to call the method of the changeable object that modifies its own attributes. This means we don't need to call the setAttribute method.
The above is the detailed content of Comparison of cookies and sessions. For more information, please follow other related articles on the PHP Chinese website!