First, let’s understand what cookies are:
Cookies are actually data that exists in your hard drive, but these data are very special and can only be submitted to the browser for help storage by web applications. We can also read the browser's cookies.
Web applications generally only store some user information and other small and temporary data in cookies. If the data volume is large, it is not suitable for storing it in cookies.
Generally, browsers will give them 40 cookies to store data for each web application, and the size of each cookie does not exceed 4K (I heard that some browsers can store large data, but we generally do not store such large data because the data extraction efficiency is not high, which affects performance)
After saying so much nonsense, the point finally came
Java accesses cookies data in browser requests through httpServletRequest interface (Let me understand the whole story of cookies here, and the code will be given later)
Each cookie has two attributes: key and value (no specific format string, so you can store data in DIY, but you should pay attention to URL encoding issues. The encoding issues will be discussed together with the code later)
If we need to store new cookies, we can new a cookie instance and submit it to the browser through httpservletRsponse, and then store it locally
Here is a common class for cookies
/* * This class can extract cookies from the browser request and perform related operations on cookies* */public class CookiesUtil extends BaseController { /** * Get cookies by name * * @param request * @param name * cookie name* @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; } } /** * Encapsulate cookies into the 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 * Save value * @author jxf */ public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int time) { // new Cookie object, key-value pair is a parameter Cookie cookie = new Cookie(name, value); // Multi-application sharing cookie.setPath("/"); // If the value of the cookie contains Chinese, the cookie needs to be encoded, otherwise the garbled code will be generated. try { URLEncoder.encode(value, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } cookie.setMaxAge(time); // Add the cookie to the Response to make it take effect response.addCookie(cookie); // After the addCookie, if the cookie with the same name already exists, the latest overwrites the old cookie return response; }With the above general class we can read and create new cookies. Here I would like to mention one thing: If the name of the new cookie already exists, it will not be added repeatedly, and the previous cookie will be overwritten.
How does the browser view the requested cookies and the returned cookies? Take a Google browser for a silly
Then we may need to delete cookies
/** * <p>Delete invalid cookies</p> * <p>Invalid?1. Obsolete 2. Not published</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);//Set the cookie validity time to 0 cookie.setPath("/");//Don't set the storage path response.addCookie(cookie); } } }Note that deleting cookies must have both time and path parameters, otherwise some browsers cannot delete them.
The above is the collection of Java's data to read and write to browser cookies. We will continue to add relevant information in the future. Thank you for your support for this site!