The difference between session and Cookie
Object |
Information size |
Save time |
Application Range |
Save location |
Session |
Small, simple data |
User activity time + a delay time (typically 20 minutes) |
Individual users |
Server-side |
Cookies |
Small, simple data |
Can be set according to need |
Individual users |
Client
|
When the 1.1 Session Object Browser accesses the server, the server creates an object (also known as the Session object, which has a unique ID number corresponding to it). And then
, the server sends an ID number to the browser (by default, it is sent using the cookie mechanism). When the browser accesses the server again, the ID number is sent
To. The server can find the corresponding session object based on the ID number. This session object is used to save the state.
The different meanings of 1.1.1 session in different environments
Session, Chinese often translated as a conversation, its original meaning refers to the beginning of a series of actions/messages, such as phone calls from the pick up phone dial to hang
A series of processes in the middle 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".
Session in the Web development environment and the semantics of the new extension, it means that a class of client and server to maintain the state between the resolution
Scheme. Sometimes the session is also used to refer to the storage structure of this solution.
1.1.2 Several ways to save session IDs
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.
If the client supports Cookie,web server when returning to response, in the header portion of response, add a "Set-cookie:
Jsessionid=xxxx "Header property, put the Jsessionid in a cookie and upload it to the client.
B Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is blocked, often
The use of a technology called URL rewrite, is the session ID appended to the URL path behind, there are two additional ways, one is as a URL path of the attached
Add information, and the other is appended to the URL as a query string. The network maintains its state throughout the interaction, and it must be possible for each client to request
Contains this session ID after the path.
C Another technique is called a form-hiding field. That is, the server automatically modifies the form and adds a hidden field so that the session can be presented when the form is submitted
The ID is passed back to the server.
What is the disadvantage of 1.1.3 URL rewriting
Use URL overrides for all URLs, including hyperlinks, form action, and redirected URLs. Each URL that references your site, and those that return
Add additional information back to the user's URL (even through indirect means, such as the Location field in server redirection).
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). Because
This, 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 bookmarks or links
Once again, the session's information is lost because the stored link contains the wrong identification information-and the sessions ID after the URL has expired.
1.1.4 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
, hidden form fields do not support the usual session tracking and can only be used in a series of specific operations, such as the checkout process for an online store.
When 1.1.5 session is created
A common mistake is that the session is created when there is client access, but the fact is that until a server-side program (such as a servlet) calls
A statement such as Httpservletrequest.getsession (true) is created.
When 1.1.6 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.
1.2 Cookie Object
When the browser sends a request to the server, the server returns a small amount of data to the browser (the data is returned to the browser as a Set-cookie message header)
, the browser stores the data on a hard disk or memory. The next time the browser accesses the server again, the data that was previously stored is sent to the server (
Sent to the server in the form of a cookie message header. In this way, you can record the data that the browser interacts with the server, which is the state.
1.2.1 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 Life
A cookie with a lifetime of browsing session is called a session cookie. 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, closes it and opens the browser again, and the cookies remain valid until more than
The set expiration time.
Cookies stored on your hard disk can be shared between different browser processes, such as two IE windows. And for cookies stored in memory, different bangs
There are different ways to handle the browser.
2.Session Relationship to Cookies
Here, an image metaphor is used to explain how the session works. Assume
Web Server: It's a store-keeping office.
HTTP Request: is a customer
Session: The locker at the store
Session ID: Save the package number card
Cookie: The customer carries a wallet that does not leave the body
Situation one: A customer (HTTP Request), for the first time to the store (Web Server), the administrator of the customer's items stored in a certain cabinet
(session), and then a number card (session ID) to the customer, as a packet voucher.
Situation two: The next time the customer (HTTP Request) comes, the number card (session ID) will be handed over to the administrator of the storage (Web Server).
The administrator finds the appropriate cabinet (session) According to the number card (session ID), and according to the request of the customer (HTTP request), the storage place (Web
Server) can remove, replace, add items in a cabinet (session), and the store (Web Server) can also have the number of customers (HTTP Request)
The cabinet (session) that corresponds to the code card and the number card is invalid.
Situation three: The memory remembers of the customer (HTTP Request) is very big, the administrator when the customer goes back (http Response) to remind the customer to remember his
Number Card (Session ID). In this way, the customer (HTTP Request) comes back with the number card the next time they come.
Situation four: The client (HTTP Request) puts the number card (session ID) that you have received into the wallet (Cookie) that you carry without leaving your body.
3.Session and Cookie Applications
3.1 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. This user ID is returned automatically when the customer is reconnected, and the server
Check it to see if it is a registered user and choose to sign in automatically so that the user can access the service by giving it a specific username and password
The resource on the device.
3.2 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. But to
For more complex customization, the site simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.
3.3 Cookies Sent
1) Create a Cookie object
2) Set Maximum aging
3 Put the cookie into the HTTP response header
If you create a cookie and send him to the browser, by default it is a session-level cookie: stored in the browser's memory, the user
Deleted after exiting the browser. If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds
Between 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. Because
This method does not modify any of the previously specified Set-cookie headers, but rather creates a new header, so we call this method Addcookie rather than
Setcookie. Also remember that the response header must be set before any document content is sent to the client.
Java Code Collection Code
Cookie cookie = new Cookie ("Duanqftest", "22222");
Cookie.setdomain ("172.20.40.73");
Cookie.setmaxage (60000);
Cookie.setpath ("/");
Response.addcookie (cookie);
javax.servlet.http.cookie[] diskcookies = Request.getcookies ();
Response.sendredirect ("Readcookie");
3.4 Cookies Read
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,
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
Will get a lot of irrelevant cookies.
Java Code Collection Code
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 ());
}
}
3.5 How to use cookies to detect first-person respondents
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
3.6 Using cookies to detect common mistakes of the first-visit person
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 an initial
Respondents may also be the result of a user removing or disabling a 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
A servlet, JSP page, and a non-Java Web application can set cookies, and any cookie in the path 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.
3.7 Attention issues using cookie Properties
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 and
These properties are not set.
Therefore, do not expect this property to be used in cookies obtained through request.getcookies. That means that you can't just set cookies by
The maximum aging, send it, in the subsequent input array to find the appropriate cookie, read its value, modify it and save it back to the cookie, so as to achieve continuous change
The variable cookie value.
3.8 How to use cookies to record access counts for individual users
1 Gets the value of the cookie in the cookie array that is designed to count the number of user accesses
2 converts the value to the INT type
3 Add a value of 1 and recreate a cookie object with the original name
4) Reset Maximum Aging
5 The new cookie output
3.9 Basic steps for session tracking
1 access to the session object associated with the current request
2 Find information related to the session
3) Store session information
4 Discard session Data
The difference between 3.10 getsession ()/getsession (True), GetSession (false)
GetSession ()/getsession (TRUE): Returns the session when the session exists, or creates a new session and returns that object.
GetSession (FALSE): Returns the session when the session exists, or it does not create a new session and returns NULL.