Java's operation of cookies is simple, mainly introduces the following resume cookie and read Cookie, and how to set cookie life cycle and cookie path problem.
Create an inanimate cookie that disappears as the browser closes, with the code as follows (don't forget the jar package you need to rely on):
HttpServletRequest request httpservletresponse Responsecookie cookie = new Cookie ("CookieName", "Cookievalue"); Response.addcookie (cookie);
Create a lifecycle cookie to set his life cycle
Cookie = new Cookie ("CookieName", "Cookievalue"); Cookie.setmaxage (3600); Set the path, the path that the project can access the cookie if the path is not set, then only the cookie path and its subpath can be accessed Cookie.setpath ("/"); Response.addcookie (cookie);
Here's how to read Cookis and read the cookie code as follows:
cookie[] cookies = request.getcookies ();//This allows you to get a cookie array for (cookie cookie:cookies) { cookie.getname ();//Get The cookie name cookie.getvalue ();//Get the cookie value}
Above is the basic read and write cookie operation. We'd better do it in real time, like adding a cookie, we're concerned about the cookie's name,value, life cycle, so we're encapsulating a function, and of course passing in a response object, Addcookie () code like this
/** * 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 C Ookie (name,value); Cookie.setpath ("/"); if (maxage>0) cookie.setmaxage (maxAge); Response.addcookie (cookie);}
When we read cookies, we want to encapsulate a function to facilitate our operation, so long as we provide the name of the cookie, we can get the value of the cookie, and with that idea, it's easy to think of encapsulating the cookie in the map, and then the following package
/** * Obtain a cookie by name * @param request * @param name Cookie name * @return */public static cookie Getcookiebyname (Httpservletreq Uest request,string name) { map<string,cookie> cookiemap = readcookiemap (request); if (Cookiemap.containskey (name)) { Cookie cookie = (cookie) cookiemap.get (name); return cookie; } else{ return null; } } /** * Enclose the Cookie in MAP * @param request * @return */private static map<string,cookie> Readcookiemap (Httpservletreque St 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;}
Java operation of Cookies