2010-01-15 60 views
3

不工作我增加了值使用饼干在Internet Explorer

Cookie testcookie = new Cookie ("test",test); 
testcookie .setMaxAge(5*60); 
response.addCookie(testcookie) ; 

到Cookie,但我没有收到在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相同的作品,cooies在IE.How启用的 代码来解决这个问题?

+0

你确定你正在访问相同的域名。即http://site.com,而不是http://www.site.com – Bozho 2010-01-15 08:32:02

+1

可能的副本http://stackoverflow.com/questions/361231/persistent-cookies-from-a-servlet-in-ie和http://stackoverflow.com/questions/1716555/setting-persistent-cookie-from-java-doesnt-work-in-ie – skaffman 2010-01-15 08:37:48

+0

雅重复的问题,但我没有得到解决方案 – sarah 2010-01-15 08:56:53

回答

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

希望它可以帮助

0

SimpleDateFormat的解决方案的工作,虽然我注意到小甜饼不当时我删除预期。似乎它在当地时间打印了时间,而格式化程序将其显示为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());