Cookies and session

Source: Internet
Author: User
Tags object header http request log return string domain access

Cookies and sessions are commonly used to implement the Http state of the technology, in the continuous use of their own understanding of it. My next discussion is based on the following sequence:

1. Why to use cookies and session

Because the HTTP protocol request process, is based on TCP/IP, when the client requests the server, the server processing, to respond, the process is stateless. In some cases, it is necessary to save some of the client's request information, identify certain 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, etc. In order to solve similar things, you need to use cookies and session.

2, Cookie and session of the specific knowledge

(1) Cookies: When the client accesses an address, the request will be sent to the server for processing, when sending the request, the browser will be the head of the page information to the server side of the processing. During processing, cookies are generated on the server side, and at the same time, some information that needs to be saved is stored in this cookie. When generating a cookie object, you need to determine the specific name and specific value, you can set the current cookie expiration time, set the expiration time, is equivalent to the persistence of the data in the cookie, at this time the cookie will be the previous cookie name, saved in the client.
If you do not set an expiration time, the current cookie's lifetime is during a browser session, and once the browser is closed, the current cookie does not exist, and the cookie information is stored in memory. On the server side, after processing, the generated cookie, along with the HTTP response, will be in the HTTP response header, plus the cookie information, and the browser, after receiving the response, will create a cookie on the client according to the cookie in the HTTP response head. The next time a client makes a request, Http is sent to the server with a Cookie that has already been stored. A domain that is created on the client so cookies can be shared as long as the cookie does not expire.

(2) Session:session is generated on the server side, stored on the server side, that is, in memory. You can set an expiration time on the generated session, and if you do not set an expiration time, the default session expiration is 30 minutes (the expiration time is slightly different on different servers, as in the case of Tomcat) but, as Sesssion builds, Generates a SessionID associated with this SessionID storage that requires cookies to complete. SessionID is named Jsessionid, and the value should be a string that neither repeats nor is easily found to mimic. SessionID will be returned to the client with this Http response and saved to the client. After the current request is issued again, the SessionID will be uploaded to the server with the Http header, and the server is given the session according to the current SessionID.

Where: Storing session state by means of cookies is just one of the ways. If the client disables cookies, many Web sites can still store the user's information. One way to handle this is URL rewriting, which attaches sesseionid directly to the back of the request address. Another way to deal with it is to use the hidden automatic way. Is that the server automatically adds a hidden field to the form, so that when the form is submitted, the Sesseionid is uploaded to the server for identification.

3, cookies and session of the specific use

Recently, when I was writing a code generator, I hoped that after I filled out the database connection information, the browser helped me to save the information so that every time I needed to use it, I would have to fill it and waste it. Here are my specific practices:

/**      * Storage Database Connection Objects      * @author gaoqing      * 2014-6-14   ;    * @param database Connection object      * @param request HTTP Request Object      ; * @param response HTTP Response Object      * @param all tables and Jsonarray objects in Jonarray database      * @ return NULL      *     private String storedatabaseinfo (database database,  & nbsp;          httpservletrequest Request, HttpServletResponse Response,             Jsonarray jonarray) {        /*          * judgment:           * (1) If the session exists and the database data is stored, it is no longer repeated save           * (2) If not, the data is stored in the session      &Nbsp;   *                
HttpSession session = Request.getsession (false);         if (session!= null && session.getattribute ("database")!= null) {&
nbsp;          //(1) If the session exists and the database data is stored, repeat save is no longer                          Log.info ("The current reply has been saved databse data, no longer repeat the save!"
");        }else{            //(2) if not, store data in session               
          session.setattribute ("database", database);
            Session.setmaxinactiveinterval (60*60);        }                 /*          * judgment:           * (1) If it is saved in request, it is no longer repeated save          * (2) if not, store the data to a Cookie          *         cookie[] cookies =
Request.getcookies ();         if ((Cookies!= null)) {             for (Cookie cookie:cookies) {                 if (Cookie.getname (). Equals ("database") {                     Log.info ("In the current cookie, the DATABSE data has been saved, No more repeat Save!
");                                         //(1) If it is saved in request, it is no longer repeated save                     
return jonarray.tostring ();                }             }        }                 //(2) if not, store the data in a Cookie          String databaseinfostr = database.getdatabasetype () + "_" + database.geturl () + "_" +  &nbs p;                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 the use protocol of Cookies         Databaseinfo.setpath ("/codegenerator/");
Set the use domain of the Cookie         Response.addcookie (databaseinfo);
                return null;    }

Where: In particular, after the cookie is generated, if you do not set the current cookie usage, regardless of whether or not to set the expiration time of the cookie, when the next visit, you will not get the name of the corresponding cookie. If the setting Databaseinfo.setpath ("/") is used in a global environment, all requests can use that Cookie if the settings and project-related domains, such as: Databaseinfo.setpath ("/codegenerator/") , the current Cookie will be used only under access to the current project.

(4) The difference between cookies and session

First, cookies are 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 using cookies, in the relatively high security requirements of information, you can use the session of the exam. After all, cookies exist on the client, and others can find and analyze them.

Finally, when the performance requirements are high, it is not appropriate to use the session, because there will always be the server, until the current sessions expire, 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, because cookies can be stored in the form of files on the client. In the verification of some logins and information interception, you can use 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.