Java operation of Cookies
Java's operation of cookies is simple, mainly introduces the establishment of cookies and read cookies, and how to set the life cycle of cookies and the path of cookies.
Create an inanimate cookie that disappears as the browser closes, with the code as follows
HttpServletRequest Request
HttpServletResponse response
Cookie 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, which can be accessed under the project, 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 a cookie and read the cookie code below
cookie[] cookies = request.getcookies ();//This allows you to 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 read-write cookie operation. In practice, we would like to do a package, such as adding a cookie, we are concerned about the name,value of the cookie, the life cycle, so to encapsulate a function, of course, to pass in a response object, Addcookie () code is as follows
/** * Set cookie * @param response * @param name Cookie name * @param value cookie values * @param MaxAge cookie life cycle in seconds */< /span>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 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 cookies by name * @param request * @param Name Cookie name * @return */ Public StaticCookiesGetcookiebyname(HttpServletRequest request,string name) {map<string,cookie> Cookiemap = readcookiemap (request);if(Cookiemap.containskey (name)) {Cookie cookie = (cookie) cookiemap.get (name);returnCookies; }Else{return NULL; } }/** * Enclose the cookie in map * @param request * @return * *Private StaticMap<string,cookie>Readcookiemap(HttpServletRequest request) {Map<string,cookie> Cookiemap =NewHashmap<string,cookie> (); cookie[] cookies = request.getcookies ();if(NULL!=cookies) { for(Cookie cookie:cookies) {Cookiemap.put (Cookie.getname (), cookie); } }returnCookiemap;}
Java operation of Cookies