Home  >  Article  >  Java  >  Detailed example of how Java reads and writes browser cookies

Detailed example of how Java reads and writes browser cookies

高洛峰
高洛峰Original
2017-01-18 13:59:301336browse

First of all, let’s understand what cookies are:

Cookies are actually data stored on your hard drive, but these data are very special and can only be submitted to the browser for storage by web applications, and we also Able to read browser cookies

Web applications generally only store a small amount of temporary data such as some user information in cookies. If the amount of data is large, it is not suitable to be stored in cookies

General browsers are suitable for Each web application will be given 40 cookies to store data, and the size of each cookie does not exceed 4K (I heard that some browser cookies can store large amounts of data, but we generally do not store such large amounts of data. , because the efficiency of data extraction is not high and affects performance)

After talking so much nonsense, the point finally comes

java accesses the cookies data in the browser request through the httpServletRequest interface (here Let’s first understand the ins and outs of cookies, the code will be given later)

Each cookie has two attributes: key, value (no specific format string, so you can DIY to store data, but pay attention to URL encoding issues , the coding issue will be discussed with the code later)

If we need to store a new cookie, we can create a new cookie instance and submit it to the browser through httpservletRsponse, and then store it locally

Given below A general class of cookie

/*
 * 该类可以从浏览器请求中提取出cookies并进行对cookis的相关操作
 * 
 */
 
public class CookiesUtil extends BaseController {
   
  /**
   * 根据名字获取cookie
   * 
   * @param request
   * @param name
   *      cookie名字
   * @return
   */
  public static Cookie getCookieByName(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;
    }
  }
 
  /**
   * 将cookie封装到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;
  }
 
  /**
   * 保存Cookies
   * 
   * @param response
   *      servlet请求
   * @param value
   *      保存值
   * @author jxf
   */
  public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int time) {
    // new一个Cookie对象,键值对为参数
    Cookie cookie = new Cookie(name, value);
    // tomcat下多应用共享
    cookie.setPath("/");
    // 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码
    try {
      URLEncoder.encode(value, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    cookie.setMaxAge(time);
    // 将Cookie添加到Response中,使之生效
    response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
    return response;
  }

With the above general class we can read and create new cookies. Here I would like to mention one more thing: if the name of the new cookie already exists in the browser, it will not be added again. , will overwrite the previous cookie

How does the browser view the requested cookie and the returned cookie? Take Google browser as an example

Java 是如何读取和写入浏览器Cookies的实例详解

Then we may need to delete cookies

/**
    * <p>删除无效cookie</p>
    * <p>无效?1.过时 2.未发布</p>
    * @param request
    * @param response
    * @param list
    */
   private void delectCookieByName(HttpServletRequest request, HttpServletResponse response,String deleteKey) throws NullPointerException {12     Map<String, Cookie> cookieMap = ReadCookieMap(request);17     for (String key : cookieMap.keySet()) { 
       if(key==deleteKey && key.equals(deleteKey)) {
         Cookie cookie = cookieMap.get(key);21         cookie.setMaxAge(0);//设置cookie有效时间为0
         cookie.setPath("/");//不设置存储路径
         response.addCookie(cookie);
       }
      }
  }

Note that cookies must be deleted at the same time There are time and path parameters, otherwise some browsers cannot delete them

The above is the data collection of Java reading and writing browser cookies. We will continue to add relevant information in the future. Thank you for your support of this site!

For more detailed examples of how Java reads and writes browser cookies, please pay attention to the PHP Chinese website for related articles!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn