Java is an example of how to read and write browser cookies _java

Source: Internet
Author: User
Tags set cookie

First we know what cookies are:

The cookie is actually a data that exists on your hard drive, but the data is very special and can only be submitted by the Web application to the browser Help store, and we can also read the browser's cookie

Web applications typically store only a few and a temporary amount of user information in a cookie, and a large amount of data is not suitable for storing cookies

The general browser for each Web application will give them 40 cookies to store the data, and the size of each cookie is not more than 4K (I heard that some browser cookies can save a large amount of data, but we generally do not save this large data, because the data extraction is inefficient, Impact performance)

So much nonsense, and then the focus finally came.

Java through the HttpServletRequest interface to access cookies in the browser request data (here first understand the origin of cookies, the code will be given together)

Each cookie has two attributes: Key, value (no specific format string, so you can store data, but note the URL coding problems, coding problems will be with the code to speak)

If we need to store a new cookie we can new a cookie instance and submit it to the browser via Httpservletrsponse, which is then stored locally

A generic class of cookies is given below

* * This class can extract cookies from the browser request and perform related operations on Cookis * * */public class Cookiesutil extends Basecontroller {/** * obtained by name Cookie * * @param request * @param name * Cookie Name * @return * * public static Cookie Getcookieb
    Yname (httpservletrequest request, String name) {map<string, cookie> Cookiemap = readcookiemap (request);
      if (Cookiemap.containskey (name)) {Cookie cookie = (cookie) cookiemap.get (name);
    return cookie;
    else {return null; /** * Package Cookies into MAP * * @param request * @return/private static map<string, cookie> 
    Readcookiemap (HttpServletRequest request) {map<string, cookie> cookiemap = new hashmap<string, Cookie> ();
    cookie[] cookies = request.getcookies ();
      if (null!= cookies) {for (cookie cookie:cookies) {cookiemap.put (Cookie.getname (), cookie);
  } return Cookiemap;
/** * Save Cookies * * @param response   * servlet Request * @param value * @author jxf/public static HttpServletResponse Setcookie (H Ttpservletresponse response, String name, string Value,int time) {//New Cookie object, key-value pair for parameter cookie = new Coo
    Kie (name, value);
    Tomcat under multiple application sharing Cookie.setpath ("/");
    If the value of the cookie contains Chinese, the cookie needs to be encoded, otherwise a garbled try {Urlencoder.encode (value, "Utf-8") is generated;
    catch (Unsupportedencodingexception e) {e.printstacktrace ();
    } cookie.setmaxage (time); Add cookies to the response to make them effective response.addcookie (cookies);
  Addcookie, if a cookie with the same name already exists, the latest overwrite old cookie return response;
 

 

 }

With the above generic class we can read and create a new cookie, and here's what I'd 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? Take a Google browser and raise a chestnut.

And then there's the possibility that we need to delete the cookie.

/**
    * <p> Delete invalid cookie</p>
    * <p> invalid? 1. Not published </p>
    * @param request
    * @param Response
    * @param list
   /private void Delectcookiebyname (HttpServletRequest request, HttpServletResponse response,string DeleteKey) throws NullPointerException {map<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 to 0
         Cookie.setpath ("/");//Do not set storage path
         Response.addcookie (cookie);}
      } 
  
 

Note Deleting cookies must have both time and path parameters or some browsers will not be able to delete

Above is the Java read and write browser cookies data collation, follow-up to continue to supplement the relevant information, thank you for your support for this site!

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.