The difference and connection between a cookie and a session

Source: Internet
Author: User


Summary:

Cookies and sessions are a very common technique for implementing HTTP states, and they are understood in constant use. My next discussion is based on the following sequence:

1. Why to use cookies and Session

Because of the HTTP protocol's request process, which is based on TCP/IP, when the client requests the server, the server processes the response, and the process is stateless. In some cases, it is necessary to save some client's request information, identify some state of the client, intelligent, targeted to analyze the habits of some clients. These times, you need to record the client's connection status, identify the status of the request, and so on. To solve something like this, you need to use a Cookie and a Session.

2. Specific knowledge of the Cookie and Session

(1) Cookies: When a client accesses an address, the request is made to the server for processing, and when the request is sent, the browser will send the header information of the page to the server side for processing. In the process of processing, the cookie is generated on the server side, and at the same time, some information that needs to be saved can be stored in this cookie. When generating a cookie object, you need to determine the specific name and the specific value, you can set the current cookie expiration time, set the expiration time is equivalent to persist the data in the cookie, at this time the cookie will be in the previous cookie name, saved on the client.

If you do not set the expiration time, the current cookie's lifetime is the browser session, and once the browser is closed, the current cookie is not present, and the cookie information is stored in memory. On the server side, after processing, the generated cookie, along with the HTTP response, will be added to the HTTP response header, with the cookie information, and the browser receives the response, and the cookie is established on the client in accordance with the cookie in the HTTP response. The next time the customer makes a request, Http will be sent to the server with the Cookie already stored. A domain that is established on the client so that cookies are shared, as long as the cookie is not expired.

(2) Session: Session is generated on the server side, stored on the server side, that is, in memory. You can set the expiration time for the generated session, and if you do not set the expiration time, the default Session expiration time is 30 minutes (it will expire slightly differently on different servers, this article is in Tomcat) However, the generation of sesssion Generates a SessionID associated with it, and this SessionID store requires a Cookie to complete. SessionID is named Jsessionid, and its value should be a string that is neither duplicated nor easily found to mimic the pattern. The SessionID will be returned to the client with this Http response, and saved in the client. Once the current request is sent again, the SessionID will be uploaded to the server with the Http header, and the server is given the corresponding Session based on the current SessionID.

Where: storing the Session state via a Cookie is only one way. If the client disables cookies, many websites can store the user's information. One way to handle this is URL rewriting, which appends sesseionid directly to the request address. Another way to handle this is to use the hidden automatic method. Is that the server is automatically in the form, adding a hidden field so that when the form is submitted, Sesseionid is uploaded to the server for identification.

3. Specific use of cookies and Session

Recently, I was writing a code generator, I hope that after I fill out the database connection information, the browser helps me to save this information, so that every time I need to use the time to fill, waste time. Here is my specific approach:

/**

* Store database Connection objects

* @param database Connection object

* @param request HTTP Requests Object

* @param response HTTP Response Object

* @param all tables and Jsonarray objects in the Jonarray database

* @return NULL Empty

*/

Private String Storedatabaseinfo (Database Database,

HttpServletRequest request, HttpServletResponse response,

Jsonarray Jonarray) {

/*

Judgment

* (1) If the session exists and the database data is stored, it will no longer be re-saved

* (2) If, not, store the data in the Session

*/

HttpSession session = Request.getsession (false);

if (session! = NULL && session.getattribute ("database")! = null) {

(1) If the session exists and the database data is stored, it is no longer re-saved

Log.info ("The current reply has saved the databse data, no longer repeat the save!") ");

}else{

(2) If, not, store the data in the Session

Session.setattribute ("Database", database);

Session.setmaxinactiveinterval (60*60);

}

/*

Judgment

* (1) If the request has been saved, it will no longer be re-saved

* (2) If, not, store the data in a Cookie

*/

cookie[] cookies = request.getcookies ();

if ((cookie = null)) {

for (Cookie cookie:cookies) {

if (Cookie.getname (). Equals ("database")) {

Log.info ("In the current cookie, the DATABSE data has been saved and no more duplicates are saved!") ");

(1) If the request has been saved, it will no longer be re-saved

return jonarray.tostring ();

}

}

}

(2) If, not, store the data in a Cookie

String databaseinfostr = Database.getdatabasetype () + "_" + database.geturl () + "_" +

Database.getport () + "_" + database.getuser () + "_" +

Database.getpassword () + "_" + database.getdatabasename () + "_" + database.gettable ();

Cookie databaseinfo = new Cookie ("database", DATABASEINFOSTR);

Databaseinfo.setmaxage (60*60);//Set the expiration time of the Cookie

Databaseinfo.sethttponly (TRUE); Set up a Cookie usage protocol

Databaseinfo.setpath ("/codegenerator/");//Setting the use domain of cookies

Response.addcookie (Databaseinfo);

return null;

}

among them: in particular, after the cookie is generated, if the use of the current cookie is not set, regardless of whether the cookie is set to expire, the next time you visit, you will not get the cookie corresponding to that name. If you set Databaseinfo.setpath ("/") to use in a global environment, all requests can use that Cookie if the settings and project-related fields, such as: Databaseinfo.setpath ("/codegenerator/") , the current Cookie is used only under access to the current project.

(4) The difference between a Cookie and a Session

First, the Cookie is stored on the client, and the Session is stored on the server side.

Second, in the preservation of relatively low-security information, you can consider the use of cookies, in the relatively high security requirements of information, you can use the Session of the exam. After all, cookies exist on the client side and others can find and analyze them.

Finally, when the performance requirements are high, it is not appropriate to use the session, because the session will always exist on the server until the current session expires, and the Cookie store is a string type of information, and the session can store any form of information, the session does not There is a limit to the access domain.

Personally, you should consider using cookies when storing relatively persistent information, as cookies can be stored on the client in the form of files. You can use the Session when you have some login verification and information interception.

Original link: http://mp.weixin.qq.com/s?__biz=MjM5OTM4NDMyMg==&mid=200647607&idx=2&sn= 1a56de4f111536efd04e935937c0262f&scene=1&srcid=1109mnfaxhwvjs034sl6j9dl&key= D4b25ade3662d64319456fb6fc86a8dec6429a4b39cf3b5c1d05539c93252199cf0ce4dabbc839e6572f83c13c866a74&ascene=1 &uin=mti5mda0ndawoa==&devicetype=webwx&version=70000001&pass_ticket= rkuvnklhhx68sbodtvdar0mlz4dblr8cpkbbxuyrvaokmstgtchpd5ji2s2rl02g

The difference and connection between a cookie and a session

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.