cookie无法在Internet Explorer中运行

时间:2010-01-15 08:25:53

标签: java internet-explorer cookies

我正在使用

向cookie添加值
Cookie testcookie = new Cookie ("test",test);
testcookie .setMaxAge(5*60);
response.addCookie(testcookie) ;

但我没有在Internet Explorer中获得cookie值。 获取cookie值的代码

Cookie cookies [] = getRequest().getCookies ();
    Cookie myCookie = null;
    if (cookies != null)
    {

        for (int i = 0; i < cookies.length; i++) 
        {
            if (cookies [i].getName().equals ("test"))
            {
                myCookie = cookies[i];
                String testval=myCookie.getValue();
            }
        }
    }

但是在Firefox中同样有效,在IE中启用了cooies。如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这些天我遇到了同样的问题,我刚刚找到了解决方案。尝试手动设置Cookie,因为javax.servlet.http.Cookie不允许您设置Expires属性:

StringBuilder cookie = new StringBuilder("test=" + test + "; ");

DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5*60);
cookie.append("Expires=" + df.format(cal.getTime()) + "; ");
cookie.append("Max-Age=" + (5*60));
response.setHeader("Set-Cookie", cookie.toString());

希望有所帮助

答案 1 :(得分:0)

SimpleDateFormat解决方案有效,但我发现在我预期的时候没有删除cookie。似乎它在当地时间打印时间,而格式化程序将其显示为GMT。如果您将日历对象设置为时区GMT并使用String.format,它将在正确的时区中格式化。

// Your values here
String name = "test";
String value = "test";
String path = "/";
int maxAge = 60;


StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append("=");
sb.append(value);

sb.append("; path=");
sb.append(path);

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.add(Calendar.SECOND, maxAge);
sb.append("; Expires=");
sb.append(String.format(Locale.US, "%1$ta, %1$td-%1$tb-%1$tY %1$tH:%1$tM:%1$tS GMT", cal));
sb.append("; Max-Age=");
sb.append(maxAge);

response.setHeader("Set-Cookie", sb.toString());