繁体   English   中英

cookie无法在Internet Explorer中运行

[英]cookie not working in Internet explorer

我正在使用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。如何解决这个问题?

这些天我遇到了同样的问题,我刚刚找到了解决方案。 尝试手动设置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());

希望能帮助到你

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM