Previously, a unified login system was used, and related logins were developed and maintained by other departments. However, due to the needs of recent projects, we need to develop a simple set of login functions. So here comes the function of a cookie. Prior to the relevant content, but this time need to develop independently, so simply record the process and the related issues encountered.
One, write cookie operation
Write the corresponding login information to the corresponding cookie//login account cookie Accountcookie=new cookie (Logincookiename,orgresult.getaccount ()); Accountcookie.setmaxage (60*30)///default cookie half-hour expiration Accountcookie.setpath ("/");//Note You need to set the request path Reponse.addcookie ( Accountcookie);
For a brief explanation of the above content,
1. Two parameters of the cookie in the construction method Key-value, nothing to say, read the corresponding key in the back to get the relevant value
2. Set the cookie's declaration period in seconds for example: The above 60*30 refers to 30 minutes
If set to a negative value, the browser process cookie (saved in memory) is disabled and the browser is closed.
If set to 0, the cookie is deleted.
3.accountcookie.setpath ("/"), it is necessary to set the request path of the cookie, if not set, the default is the current path, if the other request path to obtain the cookie, it is possible to obtain the corresponding cookie
For example, the previous request path is/org/orglist the path of the cookie is not set, the default cookie request path is/org at this point, if you request the/org path below the request can obtain the relevant cookie value
However, if your request path is/sku, then you will not be able to obtain the relevant cookie
I've made this mistake before, and I've never been in a relationship to get a cookie.
The above code is set to/then all requests will be fetched to the corresponding cookie
Second, read the cookie operation
cookie[] cookies = request.getcookies (); if (cookies = null) return null; for (Cookie c:cookies) { if (C.getname (). Equals (CookieName)) { return c.getvalue (); } }
Loop through the corresponding cookie, and find the value of the corresponding key.
The following shows information about the cookies stored in the browser:
Set the path to "/"
Not set to path, default to current path
As for how to check the browser cookie, Baidu, here do not do a specific explanation.
Some reference links are given below:
View a reference link to a browser cookie: http://blog.unvs.cn/archives/explorer-cookies-ie-chrome-firefox.html
To set a reference link for a cookie path: http://bbs.csdn.net/topics/390571141?page=1
Cookie explanation Reference Link: http://www.cnblogs.com/muzongyan/archive/2010/08/30/1812552.html
Basic methods of using cookies in Java EE