在java中获取cookie值 [英] Get cookie value in java

查看:1414
本文介绍了在java中获取cookie值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的JSP中初始化了这样的cooke,

I've initialized cooke like this in my JSP,

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);

因此,创建的所有Cookie都将具有相同的名称,但不同的用户访问时间的值不同

So, all the cookies created will have the same name, but different value for different user access time

问题1 - 在my.java中解决了

Question 1 - Solved,

我使用了

String fpath = request.getParameter("thecookie").toString();

在my.java页面中获取loc,但这显示为null我的错误是什么?

to get loc in my.java page, but this displayed null what is my mistake?

回答:我发现这里正确方法访问cookie

Answer : I found here the correct way to access cookie

问题2,

在java servlet的结尾我想停用/在Java servlet开始时传递的cookie,并说明他们是否并行使用系统的5个用户我将如何知道在my.java的最后一个用户停用哪个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?

例如,考虑

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`

现在,在my.java servlet我想停用已经在my.java开头指定的CCC值,而不影响其他Cookie值的Cookie,该如何做?

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?

推荐答案

您使用错误的方式读取Cookie ..

You are using the wrong method for reading the cookies..

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()
    }
  }
}

使用这个。无需检测特定用户的Cookie,只需将其停用即可。

use this. No need to detect the cookie for particular user just deactivate it.

这篇关于在java中获取cookie值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆