Describe the role of cookies and sessions, the differences and their respective ranges of application, how cookies, session work

Source: Internet
Author: User
Tags ranges

The difference between a cookie mechanism and a session mechanism
In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side.
At the same time, we also see that the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity, because the scenario in which the server-side holds the state needs to be stored on the client side, but there are actually other options.
Ii. differences between session cookies and persistent cookies
If you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session. This cookie, which has a lifetime of browsing session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory.
If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires.
Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.
Third, how to use the implementation of automatic login
Once a user has registered with a website, they will receive a cookie with a unique user ID. When the customer later reconnected, the user ID is automatically returned, the server checks it, determines whether it is a registered user, and automatically logs on, so that users can access resources on the server without having to give an explicit user name and password.
Iv. How to customize the site according to the user's hobby
The website may use cookies to record users ' wishes. For simple settings, the site can store the settings of the page directly in a cookie to complete the customization. For more complex customizations, however, the site simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.
V. Transmission of cookies
1. Create a Cookie Object
2. Set Maximum Aging
3. Placing a cookie into the HTTP response header
If you create a cookie and send it to the browser, by default it is a session-level cookie: stored in the browser's memory and 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 maximum aging to 0 is the command browser to delete the cookie.
Sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP request header. Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so we refer to this method as Addcookie rather than Setcookie. Also remember that the response header must be set before any document content is sent to the client.
Vi. reading of Cookies
1. Call Request.getcookie
To obtain a cookie that is sent by the browser, call HttpServletRequest's GetCookies method, which returns an array of cookie objects corresponding to the value entered by the cookie header in the HTTP request.
2. Loop the array and invoke the GetName method of each cookie until the cookie of interest is found
The cookie is associated with your host (domain), not your servlet or JSP page. Thus, although your servlet may send only 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 ());
}
}
}
Vii. How to use cookies to detect initial visitors
A. Call Httpservletrequest.getcookies () to get an array of cookies
B. Retrieving a cookie for a specified name in a loop exists and the corresponding value is correct
C. If yes, exit the loop and set the differential ID
D. Determine whether the user is a novice and perform different operations according to the distinguishing mark
Viii. use of cookies to detect common mistakes in initial visitors
You cannot think of a user as a novice simply because the cookie array does not exist in a particular data item. If the cookie array is null, the customer may be a novice, or it may be the result of a user deleting or disabling the cookie.
However, if the array is not NULL, it simply shows that the client has been to your site or domain and does not indicate that they have visited your servlet. Other Servlets, JSP pages, and non-Java Web Apps can set cookies, depending on the path setting, where any cookie is likely to be returned to the user's browser.
The correct approach is to determine if the cookie array is empty and the specified cookie object exists and the value is correct.
Nine, the use of cookie attributes of attention issues
Properties are part of the header that is sent from the server to the browser, but they do not belong to the header returned to the server by the browser.
Therefore, in addition to the name and value, the cookie attribute applies only to cookies exported from the server to the client, and the server-side cookie from the browser does not have these attributes set.
This property is therefore not expected to be available in cookies obtained through request.getcookies. This means that you cannot simply set the cookie's maximum age, issue it, look for the appropriate cookie in the subsequent input array, read its value, modify it, and save it back to the cookie to achieve the changing cookie value.
X. How to use cookies to record access counts for individual users
1. Get the value of the cookie in the cookie array specifically used to count the number of user visits
2. Convert values to int type
3. Add a value of 1 and recreate a cookie object with the original name
4. Reset Maximum Aging
5. Export the new cookie
Xi. the different meanings of the session in different environments
Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the call is from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session.
However, when the term session is associated with a network protocol, it often implies two meanings such as "connection oriented" and/or "hold State".
The semantics of the session in the Web development environment also has a new extension, meaning refers to a class of solutions to maintain state between the client and the server side. Sometimes the session is used to refer to the storage structure of this solution.
12, session of the Mechanism
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.
However, when a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID-called the session ID. If it already contains a session The ID indicates that the previous session has been created for this customer, the server will follow the session ID to retrieve the session (if it is not retrieved, may create a new one, this situation may appear on the service side has deleted the user corresponding Session object, However, the user manually appends the previous jsession parameter to the requested URL.
If the customer request does not include a session ID, a session is created for the customer and a session ID associated with the session is generated, and the session ID is returned to the client in this response.
13. Several ways to save session ID
A You can save the session ID by using a cookie so that the browser can automatically send the tag to the server in the interactive process.
B Since cookies can be artificially banned, there must be other mechanisms to pass the session ID back to the server when the cookie is banned, a technique often called URL rewriting, which appends the session ID to the URL path, with two additional ways, One is additional information as a URL path, and the other is appended to the URL as a query string. The network always maintains state throughout the interaction and must include the session ID after each client may request a path.
C Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted.
14. When was the session created?
A common mistake is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, such as a servlet.
When the session is deleted
The session is deleted under the following circumstances:
A Program Call Httpsession.invalidate ()
B Distance from the last received client sent session ID time interval exceeds the maximum effective time of the session
C Server process is stopped
Note that closing the browser only invalidates the session cookie stored in the client browser memory and does not invalidate the session object on the server side.
16. What are the drawbacks of URL rewriting?
Use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs. Each URL that references your site, and the URLs that are returned to the user (even through indirect means, such as the Location field in server redirection), add additional information.
This means that you cannot have any static HTML pages on your site (at least static pages cannot have any links to site dynamic pages). Therefore, each page must be dynamically generated using a servlet or JSP. Even if all the pages are generated dynamically, if the user leaves the session and comes back again via a bookmark or link, the session information is lost because the stored link contains the wrong identity information-the session ID after the URL has expired.
17. What are the drawbacks of using hidden form fields
You can use this method only if each page is dynamically generated with a form submission. Clicking a regular hypertext link does not result in form submission, so hidden form fields cannot support normal session tracking, only for a specific set of operations, such as the checkout process for an online store
18. Basic steps of Session tracking
1. Accessing the Session object associated with the current request
2. Find information about a session
3. Storing session information
4. Discard session Data
19, GetSession ()/getsession (True), GetSession (false) Difference
GetSession ()/getsession (TRUE): Returns the session when the session exists, or creates a new session and returns the object
GetSession (FALSE): Returns the session when the session is present, otherwise does not create a new session and returns null
20. How to relate the information to the conversation
SetAttribute replaces any previously set value, and if you want to remove a value without providing any substitution, you should use RemoveAttribute. This method triggers all Valueunbound methods that implement the value of the Httpsessionbindinglistener interface.
21. Are there any restrictions on the types of session properties?
Usually the type of session attribute is as long as an object is available. Except for null or basic types, such as Int,double,boolean.
If you want to use the value of the base type as an attribute, you must convert it to the corresponding encapsulated class object
22. How to discard session data
A Remove only 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 app):
Call invalidate to discard the entire session. Doing so will lose all session data for that user, not just session data created by our servlet or JSP pages
C Log off the user from the system and delete all sessions that belong to him or her
Call logout to log off the client from the Web server and discard all sessions associated with that user (at most one per web app). This operation has the potential to affect several different Web applications on the server.
23, using IsNew to determine whether the user is a new and old user error practices
public Boolean IsNew () method This method returns true if the session has not been associated with the client program (browser), typically because the session is new and not caused by the input client request.
However, if IsNew returns false, it simply means that he has visited the Web app before and does not mean that they have visited our servlet or JSP pages.
Because the session is user-related, it is possible for each page accessed by the user to create a conversation. So isnew to false can only say that the user has previously visited the Web app, the session can be either the current page creation, or the user previously visited the page created.
The right thing to do is to determine if a particular key exists in a session and its value is correct
24. What is the difference between the expiration of the cookie and the timeout of the session?
The timeout for a session is maintained by the server, which differs from the expiration date of the cookie. First, sessions are generally based on memory-resident cookies that are not persistent cookies and thus have no deadlines. Even if the Jsessionid cookie is intercepted and set an expiration date for it to be sent out. Browser sessions and server sessions are also very different.
25. Is the session cookie the same as the life cycle of the session object?
When the user closes the browser while the session cookie has disappeared, the session object is still stored on the server side
26. If you close the browser, the session disappears.
The program is usually when the user does log off to send a command to delete the session, however, the browser will never proactively notify the server before closing it will be shut down, so the server will not have the opportunity to know that the browser has been closed. The server retains the session object until it is inactive beyond the set interval.
The reason for this error is that most sessions use session cookies to save the conversation ID, and this session ID disappears when you close the browser, and you cannot find the original session when you connect to the server again.
If the cookie set by the server is saved to the hard disk, or if you use some means to overwrite the HTTP request header sent by the browser, send the original session ID to the server, then open the browser again to still be able to find the original session.
It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for the session, when the customer last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space.
From this we can draw the following conclusions:
Closing the browser will only leave the session cookie in the browser's memory, but it will not disappear from the session object saved on the server side, nor will the persistent cookie that has been saved to the hard disk disappear.
27. Open two browser Windows access the application will use the same session or a different session
Usually the session cookie is not used across windows, and when you open a new browser window to the same page, the system will give you a new session ID, so that the purpose of our information sharing is not reached.
At this point we can first save the session ID in the persistent cookie (by setting the session's maximum effective time), and then read it in a new window, you can get the session ID of the previous window, so that through the session The combination of a cookie and a persistent cookie allows us to implement a cross-window session trace.
28. How to use a session to show the number of visits per customer
Since the client's access count is an integer variable, it is not possible to use basic types of variables such as Int,double,boolean in the session's attribute type, so we use these basic types of encapsulated type objects as the values of the properties in the Session object
But like an integer is a non-modifiable (immutable) data structure that cannot be changed after it is built. This means that each request must create a new integer object, and then use setattribute instead of the value of the old property that existed earlier. For example:
HttpSession session = Request.getsession ();
Someimmutalbeclass value = (someimmutableclass) session.getattribute ("Someidentifier");
if (value= =null) {
Value = new Someimmutableclass (...); Create a new object that cannot be changed
}else{
Value = new Someimmutableclass (Calculatedfrom (value)); Creates a new object after recalculation of value
}
Session.setattribute ("Someidentifier", value); Overwrite the old object with the newly created object
29, how to use the session to accumulate user data
Use variable data structures, such as arrays, lists, maps, or application-specific data structures that contain write-in segments. In this way, you do not need to call setattribute unless you assign the object 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 properties without having to reset the property
}
30. Non-changing objects and changing object handling when session data is updated
Object cannot be changed because it cannot be changed once it is created, so every time you want to modify the value of a property in a session, you need to call SetAttribute ("Someidentifier", NewValue) instead of the value of the original property. Otherwise, the value of the property is not updated to change the object because it typically provides a way to modify its own properties, so whenever you want to modify the value of a property in a session, you can simply call the method that modifies the property of the object that can be changed. This means that we don't need to call the SetAttribute method.

Describe the role of cookies and sessions, the differences and their respective ranges of application, how cookies, session work

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.