The connection and difference between session and Cookie in HTTP protocol

Source: Internet
Author: User
Tags hash http request session id sessions

Specifically, the cookie mechanism uses a scenario that maintains state on the client. It is the storage mechanism of session state on the client side, and he needs the user to open the cookie support of the clients. The purpose of cookies is to resolve the problem of stateless defects in the HTTP protocol.
The session mechanism uses a solution that maintains state between the client and the server. At the same time, we also see that because of the server-side hold state of the scheme in the client also need to save an identity, so the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity. The session provides a convenient way to manage global variables
session is for each user, the value of the variable is stored on the server, with a sessionid to distinguish which user session variable, this value is accessed by the user's browser when the server is returned to the When a customer disables cookies, this value may also be set to be returned to the server by get.
As far as security is concerned: when you visit a site that uses a session and create a cookie on your own machine, it is recommended that the session mechanism on the server side be more secure. Because it does not arbitrarily read the information stored by the customer.

Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header
From a Web server standpoint, all HTTP requests are independent of the previous request. This means that each HTTP response relies entirely on the information contained in the corresponding request.
The state management mechanism overcomes some of the limitations of HTTP and allows the relationship between network clients and server-side maintenance requests. The period during which this relationship is maintained is called a session.
Cookies are small pieces of text that the server stores on the local machine and are sent to the same server with each request. The IETF RFC 2965 HTTP State Management mechanism is a generic cookie specification. The Web server sends cookies to the client using HTTP headers, and in the client terminal, the browser parses the cookies and saves them as a local file, which automatically binds any request from the same server to these cookies.
--------------------------------------------------------------------------------------------------------------- ----------------------------------------------------
Understanding the session mechanism
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.

When a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If it contains a session The ID indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved.

This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid, and. For example, WebLogic for the cookie,jsessionid= byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764 generated by the Web application, its name is Jsessionid.

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 banned. A technique that is often used is called URL rewriting, where the session ID is appended directly to the URL path, and there are two additional ways, which are additional information as a URL path, in the form of = byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764
The other is appended to the URL as a query string, in the form of http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
These two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the session ID information and normal program parameters separated.
In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.

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. such as the following form
<form name= "Testform" action= "/xxx" >
<input type= "Text" >
</form>
will be rewritten before being passed to the client.
<form name= "Testform" action= "/xxx" >
<input type= "hidden" name= "Jsessionid" value= "byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764" >
<input type= "Text" >
</form>
This technique is now less applied, and the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has contacted has used this technique.
In fact, this technique can be replaced simply by applying URL rewriting to the action.

When we talk about the session mechanism, I often hear a misunderstanding that "as soon as you close the browser, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. For the session is the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to log off when sending an instruction to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most sessions use session cookies to save the conversation ID, and after closing the browser this The session ID disappears and the original session cannot be found when connecting to the server again. If the cookie set by the server is saved to the hard disk, or if a device is used to overwrite the HTTP request header sent by the browser, and the original session ID is sent to the server, the original session can still be found by opening the browser again.

It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, when the client 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.
--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------
Talking about the difference and connection between cookie and session by Jsessionid
In some polls and the like, we tend to ask everyone to vote only for the principle of fairness, in some web development there are similar situations, we usually use cookies, such as the following code:
<% Cookie[]cookies = Request.getcookies ();
if (Cookies.lenght = = 0 | | | cookies = NULL)
Dostufffornewbie ();
has not been visited
}

Else
{
Dostuffforreturnvisitor (); I've already visited it.
}

% >

This is very easy to understand, to detect the existence of a cookie, if there is a description has been run to write the cookie code, but after running the above code, whenever the results are executed dostuffforreturnvisitor (), Through the Control Panel-internet options-Settings-view file but always do not see the generated cookie file, strange, the code is clearly not a problem, but since there is a cookie, then show it.
Cookie[]cookies = Request.getcookies ();
if (Cookies.lenght = = 0 | | | cookies = NULL)
Out.println ("Have not visited this website");
}

Else
{
for (int i = 0; i < cookie.length; i++)
{
OUT.PRINTLN ("Cookie name:" + cookies[i].getname () + "cookie value:" +
Cookie[i].getvalue ());
}
}

Operation Result:
Cookie Name:jsessionid Cookie Value:kwjhug6jjm65hs2k6 Why there is a cookie, we all know that HTTP is a stateless protocol, each time a customer reads a Web page, the server opens a new session, And the server does not automatically maintain the customer's contextual information, then how to implement the shopping cart in the online store, the session is a mechanism to save context information, it is for each user, the value of the variable is stored on the server side, through the sessionid to distinguish between different customers, The session is based on a cookie or URL rewrite, which is implemented by default using a cookie, and the system creates an output cookie called Jsessionid, which we call a session cookie to differentiate persistent cookies, Which is what we usually call cookies, note that the session cookie is stored in the browser memory, not written to the hard disk, which is what we just saw jsessionid, we usually do not see Jsessionid, But when we disable the browser cookie, the Web server passes the SessionID in the URL rewrite, and we can see strings like sessionid=kwjhug6jjm65hs2k6 in the address bar.
Understanding the principle, we can easily distinguish between persistent cookies and session cookies, the online discussion on the security of the two is also clear, session cookie for a session, sessions end The cookie disappears, and the persistent cookie is just a piece of text (usually encrypted) that exists on the client's hard drive, and may be subject to cookie spoofing and cross-site scripting attacks against cookies, which are not as secure as session cookies.
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 SessionID, so that the purpose of our information sharing is not reached, At this point we can first save the SessionID in the persistent cookie, and then read it in a new window, we can get the previous window SessionID, so through the session cookie and persistent The combination of cookies allows us to implement a cross-window session tracking (conversation tracking).
In some Web development books, the session and cookie are often simply used as two kinds of parallel HTTP transmission information, session cookies located on the server side, the persistent cookie is located on the client, But the session is based on a cookie, understand the relationship between the two and the difference, we will not be difficult to choose the right technology to develop Web service.

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.