使Cookie标头中的字符串过期 [英] Expires string in cookie header

查看:72
本文介绍了使Cookie标头中的字符串过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个简单的问题,但是我似乎找不到答案。

Simple question I think, but I just can't seem to find an answer.

我正在使用Cookie类在Java Servlet中编写cookie,在响应标头中发送给浏览器,如下所示:

I am writing a cookie in a Java Servlet with the Cookie class which is sent to the browser in the response headers like the following:

Set-Cookie: test=somevalue; Domain=.mydomain.org; Expires=Thu, 06-Jan-2011 18:45:20 GMT; Path=/

我正在通过Servlet 2.5 API中的Cookie类来执行此操作。我需要在此字符串的末尾添加 HTTPOnly,而Servlet 2.5 API不支持该字符串。没问题,我将手动创建String并将 HTTPOnly附加到末尾...

I am doing this via the Cookie class in the Servlet 2.5 API. I need to add "HTTPOnly" to the end of this String, which the Servlet 2.5 API does not support. No problem, I'll just create the String manually and append "HTTPOnly" to the end...

但是,这样做的时候,我遇到的挑战是首先使用.setMaxAge(3600)设置 Expires标头,以创建该字符串的 Expires部分。但是,由于我无法使用Cookie类,因此需要创建该过期部分的值。

However, in doing so, the challenge I ran into is that to set the "Expires" header there in the first place, I used .setMaxAge(3600), which creates the "Expires" part of that String. However, since I can't use the Cookie class, I need to create the value of of that "Expires" portion.

因此,基本上,将 3600格式设置为 2011年1月6日星期四,格林尼治标准时间?

注意:我可能会找出正确的DateFormat模式,但我希望有一种更好的方法。另一个想法:和以前一样使用Cookie类,然后以编程方式将Cookie转换为相应的标头字符串,然后将 HTTPOnly附加到末尾。但是我不知道采取任何方法来获取Cookie对象并将其转换为相应的String值。

Note: I could probably figure out the correct pattern with DateFormat, but I was hoping there was a better way to do it. Another thought: Use the Cookie class as before then just convert the Cookie into the corresponding header string programatically, then just append "HTTPOnly" to the end. But I am not aware of any way to take the Cookie object and convert it to the corresponding String value.

因此,可选地,如何获取Cookie对象并以编程方式将其转换为相应的String值?

谢谢!

推荐答案

类似这样的东西:

Date expdate = new Date ();
expdate.setTime (expdate.getTime() + (3600 * 1000));
String cookieExpire = "expires=" + expdate.toGMTString();
...

..并且由于toGMTString()已弃用

.. and since toGMTString() is deprecated

Date expdate= new Date();
expdate.setTime (expdate.getTime() + (3600 * 1000));
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", java.util.Locale.US);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String cookieExpire = "expires=" + df.format(expdate);

这篇关于使Cookie标头中的字符串过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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