Some understanding of the session and cookies

Source: Internet
Author: User
Tags session id sessions set cookie java web

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 the server-side retention scheme is also required to keep an identity at the client, the session mechanism may need to use the cookie mechanism to save the identity, but there are other options, such as rewriting the URL and hiding the form field.

*************************************************************************************
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 you set an expiration time (Setmaxage (60*60*24)), the browser saves the cookie to the hard disk and then opens the browser again after it is closed, and the cookies are still 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. (test pass under IE)

*************************************************************************************
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 is reconnected later, 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 give a clear username and password to access the 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 (the server automatically creates a cookie and jsessionid as a key, The value of the SessionID is sent to the client browser memory as value, 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 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. Iterate over the array, call each cookie's GetName method until you find the cookie that interests you, and the cookie is related to 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: (login.jsp page cookie Implementation user name username fill in)
LOGIN.JSP:

<%
String username = "";
Read the cookie file from the client on the hard drive
cookie[] cookies = request.getcookies ();
if (cookies = = null) {
Username = "";
}
else{
for (int i = 0; i < cookies.length; i++) {
if ("USERNAME". Equalsignorecase (Cookies[i].getname ())) {
Username = Cookies[i].getvalue ();
}
}
%>

<form name= "Login" method= "POST" action= "Login.do" >
&LT;TD width= "100%" bgcolor= "#CCCCCC" colspan= "2" >
<p align= "Left" > Username <br>
<input type= "text" name= "username" value= "<%=username%>" >
</p>
<p align= "left" > Password <br>
<input type= "password" name= "password" >
</p>
<p align= "Left" >
<input type= "Submit" name= "Submit" value= "OK" >
<input name= "reset" type= "reset" value= "Cancel" >
</p>
</form>

Loginaction:
Put the correct USERNAME into the C1 object and use "USERNAME" as the key identifier
Cookie c1= New Cookie ("USERNAME", Logindto.getusername ());
If you do not set the time, the cookie is a session cookie and is not written to the client hard disk
C1.setmaxage (60*60*24);
Response.addcookie (C1);

*************************************************************************************
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 as a 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 interest.

But 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. If it already contains a session ID indicates that the session has previously been created for this customer, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one, which may appear to have been deleted by the service side of the user's corresponding session object. However, the user artificially attaches the last jsession parameter after the requested URL. 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 at the same time, 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 misconception is that the session is created when there is client access, but the fact is that the statement is created until a server-side program calls Httpservletrequest.getsession (true).

Note If the JSP does not display the use of <% @page session= "false"%> closes the session, the JSP file will automatically be added to the servlet when it is translated into a language HttpSession Httpservletrequest.getsession (true); This is also the origin of the session object implied in the JSP.

Because session consumes memory resources, you should close it in all JSPs if you do not intend to use it.

*************************************************************************************
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

Again, note that closing the browser only invalidates the session cookie stored in the client browser's memory, and does not invalidate the server-side session object unless the server end is in session expiration time.

*************************************************************************************
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 series 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
*************************************************************************************

The SetAttribute method replaces the value set in the last setattribute, and if you want to remove a value without providing any substitution, use removeattribute. This method triggers all Valueunbound methods that implement the values of the Httpsessionbindinglistener interface.

*************************************************************************************
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 the session data created by our 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 yet contacted the client (browser), that is, if the server-side program has not yet returned to the client, typically because the session was new and not caused by the input customer request. But if IsNew returns false, it simply means that he has previously visited web apps, and does not mean that they have visited our servlet or JSP pages.

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 correct approach is to determine whether a particular key exists in a session and whether its value is correct. (Pending test)

*************************************************************************************
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, a session is generally based on a memory-resident cookie that is not a persistent cookie, and therefore does not have a deadline. 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 until its expiration time.

*************************************************************************************
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. It is precisely because the browser does not cause the session to be deleted, forcing the server to set a failure time for the 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 will be deleted 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.


Add: Then how do you delete the session when the browser closes?

Strictly speaking, this is not to be done. One way to do this is to use JavaScript code window.oncolose on all client pages to monitor the browser's shutdown action, and then send a request to the server to delete the session. But there is still nothing to do about the browser crashing or the forced killing of the process by unconventional means.

*************************************************************************************
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 that the purpose of our information sharing will not be achieved. For the session, the ID is not recognized, so different browsers, different windows open, and different ways of storing cookies (such as conversation cookies and persistent cookies) will have an impact on the answer to this question.

(Test in IE, open two browsers (not a new window, is the direct launch of the browser two times), the SessionID is also different)

To implement a cross window session trace, we can first save it in the persistent cookie (by setting the maximum effective time for the sessions), and then read it in a new window, and we can get an ID on the last window. This allows us to implement a cross window session trace through the combination of the sessions cookie and the persistent cookie. (Pending test)

*************************************************************************************
28, how to use the session to show the number of visits per customer
*************************************************************************************

Because the customer's access count is an integer variable, but the type of the session's properties cannot use the basic types of variables such as Int,double,boolean, we 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 overwrite the value of the old property that existed before. For example:

Integer value = (integer) request.getsession (). getattribute ("cout");
if (value = = null) {
Value = new CountClass (...); New Create a non-changed object
}else{
Value = new CountClass (calculated (value)); Create a new object after recalculation of value
}
Request.getsession (). setattribute ("cout", 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:

List List_check = (list) request.getsession (). getattribute ("Ids_go");
if (List_check = = null) {
List_check = new List (...);
Request.getsession (). setattribute ("Ids_go", List_check);
}else{
List_check. Clear ();///If the object already exists, update its properties without having to reset the property
}
List list_check1 = (list) request.getsession (). getattribute ("Ids_go");
System.out.println (List_check1.size ());//At this time the size is 0

*************************************************************************************
30, cannot change the object and can change the object in session data update when the different processing
*************************************************************************************

You cannot change an object because once created, you cannot change it, so each time you want to modify the value of a property in a session, you need to invoke setattribute ("Someidentifier", NewValue) instead of 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 whenever you want to modify the value of a property in a session, you can simply invoke the method of modifying its own properties for the modifiable object, which means that we do not need to invoke the SetAttribute method.

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.