在java中获取cookie值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22804409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get cookie value in java
提问by
I've initialized cooke like this in my JSP,
我已经在我的 JSP 中像这样初始化了 Cooke,
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie thecookie = new Cookie("thecookie", loc);
thecookie.setMaxAge(60*60*24);
response.addCookie(thecookie);
So, all the cookies created will have the same name, but different value for different user access time.
因此,创建的所有 cookie 将具有相同的名称,但针对不同的用户访问时间具有不同的值。
At the ending of java servlet I want to deactivate/kill the cookie that has been passed at the beginning of java servlet and say if they are 5 users using the system in parallel how will I know which cookie to deactivate for which user in the last of my.java?
在 java servlet 结束时,我想停用/杀死在 java servlet 开头传递的 cookie,并说如果他们是 5 个并行使用系统的用户,我将如何知道最后为哪个用户停用哪个 cookie my.java 的?
for example, consider
例如,考虑
User 1 : cookie name `thecookie` value `AAA`
User 2 : cookie name `thecookie` value `BBB`
User 3 : cookie name `thecookie` value `CCC`
User 4 : cookie name `thecookie` value `DDD`
User 5 : cookie name `thecookie` value `EEE`
Now, at the end of my.java servlet I want to deactivate the cookie with value CCC that has been assigned at the beginning of my.java without disturbing other cookie values, how to do this?
现在,在 my.java servlet 的末尾,我想在不干扰其他 cookie 值的情况下停用在 my.java 开头分配的值为 CCC 的 cookie,该怎么做?
采纳答案by JavaLearner
You are using the wrong method for reading the cookies..
您正在使用错误的方法来读取 cookie..
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cookieName")) {
//do something
//value can be retrieved using #cookie.getValue()
}
}
}
use this. No need to detect the cookie for particular user just deactivate it.
用这个。无需检测特定用户的 cookie,只需将其停用即可。
回答by shrikant
Cookie[] cookies = request.getCookies();
int i = 0;
for (Cookie cookie : cookies ) {
Sytem.out.println(cookies[i].getName());
Sytem.out.println(cookies[i].getValue());
i++;
}
回答by Pavel Vlasov
Ready to use generic method:
准备使用泛型方法:
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
回答by Dmitry Kaltovich
In kotlin it will be much shorter:
在 kotlin 中,它会更短:
fun HttpServletRequest.getCookie( name: String) = cookies.firstOrNull { it.name == name }