Detailed explanation of cookies in java
Java's operation of cookies is relatively simple. It mainly introduces the issue of establishing cookies and reading cookies, as well as how to set the life cycle of cookies and the path of cookies.
Create a lifeless cookie, that is, a cookie that disappears as the browser closes. The code is as follows
HttpServletRequest request HttpServletResponse responseCookie cookie = new Cookie("cookiename","cookievalue");response.addCookie(cookie);Create a life cycle cookie below, which can set its life cycle
cookie = new Cookie("cookiename","cookievalue"); cookie.setMaxAge(3600); //Set the path, this path, that is, the cookie can be accessed under the project. If the path is not set, then only the cookie path and its subpath can be accessed by setting the cookie path.setPath("/");response.addCookie(cookie);The following describes how to read cookies. The cookie code is as follows
Cookie[] cookies = request.getCookies();// This way you can get an array of cookies for(Cookie cookie: cookies){ cookie.getName();// get the cookie name cookie.getValue();// get the cookie value}The above is the basic operation of reading and writing cookies. In reality, it is best to encapsulate, such as adding a cookie. We focus on the name, value, and life cycle of the cookie. Therefore, encapsulating a function, of course, you also need to pass in a response object. The addCookie() code is as follows
/** * Set cookie * @param response * @param name cookie name * @param value cookie value * @param maxAge cookie life cycle in seconds */public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){ Cookie cookie = new Cookie(name,value); cookie.setPath("/"); if(maxAge>0) cookie.setMaxAge(maxAge); response.addCookie(cookie);}When reading cookies, in order to facilitate our operations, we want to encapsulate a function. As long as we provide the name of the cookie, we can get the value of the cookie. With this idea, it is easy to encapsulate the cookie into the map, so we encapsulate the following
/** * 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;}Thank you for reading, I hope it can help you. Thank you for your support for this site!