How Java is read and written to browser cookies

Source: Internet
Author: User

First we know what cookies are:

A cookie is actually a data that exists on your hard drive, but this data is unique and can only be submitted by the Web app to the browser help store, and we can also read cookies from the browser

Web applications generally store only a small amount of temporary data, such as some user information, in a cookie, which is not suitable for storing cookies in a large amount of data.

The General browser gives them 40 cookies for each Web app to store the data, and the size of each cookie does not exceed 4K (it is said that some browser cookies can hold a large amount of data, but we generally do not have such large data, because the data extraction efficiency is not high, Impact performance)

Talking so much nonsense, and then the focus finally came.

Java accesses the cookie data in the browser request via the HttpServletRequest interface (see the cookie context first, the code will be given later)

Each cookie has two attributes: Key, value (no specific format string, so you can save the data DIY, but pay attention to the URL coding problem, coding problem will be with the code to talk about later)

If we need to store a new cookie we can new a cookie instance and submit it to the browser via Httpservletrsponse to store it locally

A general class of cookies is given below

/** This class can extract the cookies from the browser request and perform the operation on the Cookis **/ Public classCookiesutilextendsBasecontroller {/*** Get a cookie by name * *@paramRequest *@paramName * Cookie *@return     */     Public StaticCookie Getcookiebyname (httpservletrequest request, String name) {Map<string, cookie> cookiemap =Readcookiemap (Request); if(Cookiemap.containskey (name)) {Cookie Cookie=(Cookie) cookiemap.get (name); returncookies; } Else {            return NULL; }    }    /*** Enclose the cookie in map * *@paramRequest *@return     */    Private StaticMap<string, cookie>Readcookiemap (HttpServletRequest request) {Map<string, cookie> cookiemap =NewHashmap<string, cookie>(); Cookie[] Cookies=request.getcookies (); if(NULL!=cookies) {             for(Cookie cookie:cookies) {cookiemap.put (Cookie.getname (), cookie); }        }        returnCookiemap; }    /*** Save Cookies * *@paramResponse * servlet request *@paramValue * Save values *@authorJXF*/     Public StaticHttpServletResponse Setcookie (httpservletresponse response, string name, String value,intTime ) {        //new A Cookie object with key-value pairs as argumentsCookie cookie =NewCookie (name, value); //Tomcat under multi-app sharingCookie.setpath ("/"); //if the value of the cookie contains Chinese, it is necessary to encode the cookie, otherwise it will cause garbled        Try{Urlencoder.encode (value,"Utf-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace ();        } cookie.setmaxage (time); //Add a cookie to the response to make it effectiveResponse.addcookie (cookie);//Addcookie, if a cookie with the same name already exists, the latest overwrite of the old cookie        returnresponse; }

With the general class above we can read and create new cookies, and here I would like to mention: the name of the new cookie if the browser already exists, it will not be added again, overwriting the previous cookie

How does the browser view the requested cookie and the returned cookie? Get a chestnut with Google Chrome

Then we may need to delete the cookie

1 /**2 * <p> Delete invalid cookie</p>3 * <p> Invalid? 1. Obsolete 2. Not published </p>4      * @paramRequest5      * @paramResponse6      * @paramList7      */8     Private voidDelectcookiebyname (httpservletrequest request, HttpServletResponse response,string DeleteKey)throwsNullPointerException { Amap<string, cookie> cookiemap =Readcookiemap (request); -           for(String key:cookieMap.keySet ()) { -              if(Key==deletekey && key.equals (DeleteKey)) { +Cookie cookie =Cookiemap.get (key); +Cookie.setmaxage (0);//Set cookie valid time is 0 ACookie.setpath ("/");//Do not set the storage path at Response.addcookie (cookie); -              } -             }  -}

Note Deleting a cookie must have both time and path parameters, or some browsers will not delete

Finally, have to mention, wrote so, for your useful on to a praise!!!

How Java is read and written to browser cookies

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.