Home Java javaTutorial Detailed example of how Java reads and writes browser cookies

Detailed example of how Java reads and writes browser cookies

Jan 18, 2017 pm 01:59 PM

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;
  }
Copy after login

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);
       }
      }
  }
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles