The difference between cookie mechanism and session mechanism
*************************************************************************************
Specifically, the cookie mechanism is a scheme for maintaining state on the client side, and the session mechanism uses the scheme of maintaining state at the server end.
At the same time, we also see that because only the server-side maintenance of the state of the scheme in the client also need to save an identity, so session
The mechanism may need to use the cookie mechanism to save the identity, but there are actually other options
*************************************************************************************
The difference between a session cookie and a persistent cookie
*************************************************************************************
If you do not set an expiration time, the cookie life cycle is the duration of the browser session, and the cookie disappears when the browser window is closed. This lifetime is called a session cookie for browsing session cookies. Session cookies are generally not stored on the hard drive but are kept in memory.
If an expiration time is set, the browser saves the cookie to the hard disk and then opens the browser again after it is closed, and the cookies remain valid until the set expiration time is exceeded.
Cookies stored on your 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
*************************************************************************************
When a user registers with a Web site, he or she receives a cookie with a unique user ID. When the customer later reconnected, this
The user ID is automatically returned, the server checks it, determines whether it is a registered user and chooses to log on automatically, allowing the user to provide a clear username and password to access resources on the server.
*************************************************************************************
Iv. How to customize the site according to the user's hobby
*************************************************************************************
A Web site can use cookies to record the user's wishes. For simple settings, a Web site can store the settings of a page directly in a cookie to complete 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.
*************************************************************************************
Five, the sending of cookies
*************************************************************************************
1. Create a Cookie Object
2. Set Maximum Aging
3. Put cookies 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 the maximum limitation 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, but instead creates a new header, we call this method Addcookie, not Setcookie. Also remember that the response header must be set before any document content is sent to the client.
Six, the reading of cookies
*************************************************************************************
1. Call Request.getcookie
To get a cookie sent by the browser, you need to call the HttpServletRequest GetCookies method, which returns an array of cookie objects that corresponds to the value entered by the cookie header in the HTTP request.
2. Cycle the array, call the GetName method of each cookie until you find an interesting cookie
Cookies are associated with your host (domain), not your servlet or JSP page. Thus, although your servlet may only send a single cookie, you may get a lot of irrelevant cookies.
For example:
String cookiename = "UserID";
Cookie cookies[] = request.getcookies ();
if (cookies!=null) {
for (int i=0;i<cookies.length;i++) {
Cookie cookie = cookies[i];
if (Cookiename.equals (Cookie.getname ())) {
Dosomethingwith (Cookie.getvalue ());
}
}
}
Vii. How to use cookies to detect the first-visit person
*************************************************************************************
A. Call Httpservletrequest.getcookies () get the cookie array
B. Retrieving the cookie for the specified name in the loop and whether the corresponding value is correct
C. If so, exit the loop and set the distinguished identity
D. Determine whether a user is a beginner and perform different operations based on the identification of the difference
*************************************************************************************
Use cookies to detect common mistakes of first-visit people
*************************************************************************************
The user is not considered a beginner 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 the user removing or disabling the cookie.
However, if the array is not NULL, it simply shows that the customer has been to your site or domain and does not indicate that they have visited your servlet. Other servlet, JSP pages, and non-Java WEB applications can set cookies, which, depending on the path setting, may be returned to the user's browser.
The correct approach is to determine whether the cookie array is empty and that the specified cookie object exists and that the value is correct.
*************************************************************************************
Nine, the use of cookies attribute attention to the problem
*************************************************************************************
Properties are part of the header that is sent from the server to the browser, but they do not belong to the header returned by the browser to the server.
Therefore, in addition to the name and value, the cookie property applies only to cookies that are exported from the server to the client, and the server-side cookies from the browser do not set these properties.
Therefore, do not expect this property to be used in cookies obtained through request.getcookies. This means that you can't just emit it by setting the maximum duration of the cookie, look for the appropriate cookie in the subsequent input array, read its value, modify it, and save it back to the cookie to implement the changing cookie value.
*************************************************************************************
X. How to use cookies to record access counts for individual users
*************************************************************************************
1. Get the value of a cookie in the cookie array that is designed to count the number of user accesses
2. Convert value to int type
3. Add a value of 1 and recreate a cookie object with the original name
4. Reset Maximum Aging
5. Output a new cookie
*************************************************************************************
The different meanings of session in different environment
*************************************************************************************
Session, Chinese often translated as a conversation, its original meaning refers to the beginning of a series of actions/messages, such as the phone is from the phone to pick up the telephone to hang up the middle of a series of processes can be called a sessions.
However, when the term session is associated with a network protocol, it often implies two meanings such as "connection-oriented" and/or "hold State".
Session in the Web development environment and the semantics of the new extension, it means that a class used to maintain the state between the client and server solution. Sometimes the session is also used to refer to the storage structure of this solution.
*************************************************************************************
12, session of the Mechanism
*************************************************************************************
The session mechanism is a server-side mechanism in which the server uses a structure similar to a hash table (or perhaps a hash table) to hold the 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 a session ID. and if it already contains a session ID, it has previously been created for this customer The session, the server will follow the session ID to retrieve this session to use (if not retrieved, may create a new one, this situation may appear in the service side has deleted the user corresponding session object, but the user artificially in the requested URL Appended with the previous jsession parameter).
If the customer request does not contain a session ID, a session is created for this customer and a sessions ID associated with this is generated, which is returned to the client for saving in this response.
*************************************************************************************
13, save the session ID several ways
*************************************************************************************
A A cookie can be used to save the session ID so that the browser automatically sends the identity to the server in accordance with the rules during the interaction.
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 blocked, often using a technique called URL rewriting, which appends the session ID to the URL path, with two additional methods. One is additional information as a URL path, and the other is appended to the URL as a query string. The network maintains its state throughout the interaction, and it must include the session ID after each path that the client may request.
C Another technique is called a form-hiding field. 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 will the session be created?
*************************************************************************************
A common error is that the session is created when there is a client access, but the fact is that a statement such as Httpservletrequest.getsession (true) is not created until a server-side program, such as a servlet, is invoked.
*************************************************************************************
When the session is deleted
*************************************************************************************
The session is deleted under the following circumstances:
A Program Call Httpsession.invalidate ()
B The interval that received the session ID sent by the client exceeds the maximum active time
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 server-side session object.
*************************************************************************************
16. What is the disadvantage of URL rewriting
*************************************************************************************
Use URL overrides for all URLs, including hyperlinks, form action, 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 the site's dynamic pages). Therefore, each page must be dynamically generated using a servlet or JSP. Even if all the pages are dynamically generated, if the user leaves the session and comes back through a bookmark or link, the session's information is lost because the stored link contains the wrong identification information-and the sessions ID after the URL has expired.
*************************************************************************************
17. What are the disadvantages of using hidden form fields?
*************************************************************************************
This method can be used only when each page is dynamically generated with form submission. Click the General <a HREF ... > Hypertext links do not produce form submissions, so hidden form fields do not support regular session tracking and can only be used in a range of specific operations, such as the checkout process for an online store
*************************************************************************************
18, the basic steps of Session tracking
*************************************************************************************
1. Accessing the Session object associated with the current request
2. Find information related to a session
3. Store session Information
4. Discarding 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 exists, or it does not create a new session and returns null
*************************************************************************************
20. How to associate information with a session
*************************************************************************************
SetAttribute replaces any previously set value, and you should use RemoveAttribute if you want to remove a value without providing any substitution. This method triggers all the values that implement the Httpsessionbindinglistener interface Valueunbound
Method.
*************************************************************************************
21. What are the restrictions on the type of session properties?
*************************************************************************************
Typically, the type of a session property can be as object. In addition to null or basic types, such as Int,double,boolean.
If you want to use a value of the base type as a property, you must convert it to the appropriate encapsulated class object
*************************************************************************************
22. How to discard session data
*************************************************************************************
A Only remove data created by the servlet you wrote:
Call RemoveAttribute ("key") discards the value associated with the specified key
B To delete an 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 our
Session data created by a servlet or JSP page
C Log off the user from the system and delete all sessions that belong to him or her
Call logout to log off the customer from the Web server and discard all sessions associated with the user (up to one per Web application). This operation may affect several different Web applications on the server
*************************************************************************************
23, using IsNew to determine whether the user is a new and old users of the wrong approach
*************************************************************************************
public Boolean IsNew () method This method returns true if the session has not been contacted with the client (browser), typically because the session is new and not caused by the input customer request.
But if IsNew returns false, it simply means that he has previously visited the Web application and does not mean that they have visited our servlet or JSP page.
Because sessions are user-related, it is possible to create a session on every page that is accessed before the user. So isnew to false can only say that the user has previously visited the Web application, the session can be created by the current page, or by a page that the user has visited before.
The right thing to do is to determine whether a particular key exists in a session and whether its value is correct
*************************************************************************************
24. What's the difference between a Cookie's expiration and a session timeout?
*************************************************************************************
The timeout for a session is maintained by the server, which differs from the expiration date of the cookie. First, the session is typically based on a cookie that resides in memory
is not a persistent cookie, so there is no expiration date. Even if the Jsessionid cookie is intercepted and set a expiration date for it to send out. Browser sessions and server sessions can also be very different.
*************************************************************************************
25, the session cookie and Session object life cycle is 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. If you just close the browser, the session disappears.
*************************************************************************************
The program is generally in the log off when the user sent a command to delete session, but the browser never actively before the shutdown to notify the server it will be closed, 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 of the session cookies are used to save the sessions ID, and when the browser is closed it disappears, and when you connect to the server again, you can't find the original one.
If the server-set cookie is saved to the hard disk, or if you use some means to overwrite the HTTP request header issued by the browser, and send the original session ID to the server, you can still find the original session by opening the browser again.
is precisely because the browser does not cause the session to be deleted, forcing the server to set a failure time for sessions, when the client last time to use more than this expiration time, the server can assume that the client has stopped the activity before the session Remove to conserve storage space.
From this we can draw the following conclusions:
Turning off the browser, only the session cookie in the browser-side memory disappears, but does not make the session object saved on the server end disappear, nor does it make the persistent cookie that has been saved to the hard disk disappear.
*************************************************************************************
27, open two browser window to access the application will use the same session or different sessions
*************************************************************************************
Usually the session cookie is not used across windows, and when you open a new browser window into the same page, the system will give you a new sessions ID, so we can not achieve the purpose of information sharing.
At this point, we can save the session ID in the persistent cookie (by setting the maximum effective time for sessions), and then read it in a new window, and then we can get an ID on the last window, which is passed The combination of Ersistent cookies allows us to implement a cross window session tracking.
*************************************************************************************
28, how to use the session to show the number of visits per customer
*************************************************************************************
Because the customer's access count is a variable of an integer type, the type of the base type of int, double, Boolean cannot be used in the session's property types, so we need to use the encapsulated type object of these basic types as the value of the property in the Session object.
But like an integer is a immutable data structure: it cannot be changed after it is built. This means that each request must create a new integer object, and then use setattribute to replace 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 (...); New Create a non-changed object
}else{
Value = new Someimmutableclass (Calculatedfrom (value)); Create a new object after recalculation of value
}
Session.setattribute ("Someidentifier", value); Overwrite original old object with 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 WordPad. In this way, you do not need to invoke setattribute unless you first assign an object. 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, the property is updated without the need to reset the property
}
*************************************************************************************
30, cannot change the object and can change the object in session data update when the different processing
*************************************************************************************
The object cannot be changed because it cannot be changed once it is created, so each time you want to modify the value of the property in the session, you need to
Call SetAttribute ("Someidentifier", NewValue) to replace the value of the existing property, otherwise the value of the property will not be updated
You can change an object because it generally provides a way to modify its own properties, so each time you want to modify the value of a property in a session
, just call the method that changes the properties of the object that you want to modify. Which means we don't need to tune
With the SetAttribute method.
*************************************************************************************