Detailed example of how Java reads and writes browser cookies
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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. ...

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...

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...

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

Start Spring using IntelliJIDEAUltimate version...

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...

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...

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...
