Session and Cookie are familiar to web development, namely unfamiliar, familiar refers to often encounter, such as Request.getsession (), Request.getcookie (), Session.setattribute () And so on can see, unfamiliar means never know what they really are, can not say why. In fact, I am also confused in this problem for a long time, I hope to borrow this essay to rationale.
Because HTTP is a stateless protocol, which means that there is no memory ability to things, if the subsequent operation requires the previous information (classic such as shopping cart), then need to re-pass, which causes the amount of data per connection to increase, so you need a technology to maintain the HTTP connection, Then the session and the cookie appeared.
First look at the cookie, first understand its role: when the user through the HTTP access to the server, the server will return a k/v value to the client (browser), and the data to add some constraints (that is, in addition to the Name/value parameters), then the data returned to the browser to do? Of course, in order to determine the next visit is not the same person, if it is the same person, then consider some of the program design can be optimized, like the person who has just come to your home, immediately back, of course, and the reception of the new guests are not the same.
So how does a cookie work, and in servlet technology, very good cookie support has been provided.
Here is the cookie class source section in the Java servlet package, where you can see the properties of the cookie.
We can set our own cookie property, the new cookie (string name, string value), but be careful not to be the same as the reserved field in version 0 or 1, otherwise throw an exception, the source code is as follows:
string GetCookie (cookie[] cookies, string key) {if(Cookies! =NULL){ for(Cookie cookie:cookies) {if(Cookie.getname (). Equals (key)) {returnCookie.getvalue (); } } } return NULL;} @override Public voiddoget (httpservletrequest request, httpservletresponse response) {cookie[] cookies =request.getcookies (); String UserName= GetCookie (Cookies, "username")); String Userage= GetCookie (Cookies, "Userage")); if(UserName = =NULL) {Response.addcookie (NewCookies ("UserName", "Larry")); } if(UserName = =NULL) {Response.addcookie (NewCookies ("Userage", "24")); } response.getheaders ("Set-cookie");}
View Code
The session exists on the server side, and the cookie is present on the client.
<Web> Session and Cookies