`

【转】JAVA中Cookie MaxAge属性及其使用

阅读更多

详见: http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp98

API文档中对MaxAge的描述:

public void setMaxAge(int expiry)

Sets the maximum age of the cookie in seconds.

A positive valueindicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie’s current age.

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Parameters: expiry – an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie

(maxAge 可以为正数,表示此cookie从创建到过期所能存在的时间,以秒为单位,此cookie会存储到客户端电脑,以cookie文件形式保存,不论关闭浏览器或关闭电脑,直到时间到才会过期。

可以为负数,表示此cookie只是存储在浏览器内存里,只要关闭浏览器,此cookie就会消失。maxAge默认值为-1。

还可以为0,表示从客户端电脑或浏览器内存中删除此cookie。)

如果maxAge属性为正数,则表示该Cookie会在maxAge秒之后自动失效。浏览器会将maxAge为正数的Cookie持久化,即写到对应的Cookie文件中。无论客户关闭了浏览器还是电脑,只要还在maxAge秒之前,登录网站时该Cookie仍然有效。

如果maxAge为负数,则表示该Cookie仅在本浏览器窗口以及本窗口打开的子窗口内有效,关闭窗口后该Cookie即失效。maxAge为负数的Cookie,为临时性Cookie,不会被持久化,不会被写到Cookie文件中。Cookie信息保存在浏览器内存中,因此关闭浏览器该Cookie就消失了。Cookie默认的maxAge值为-1。

如果maxAge为0,则表示删除该Cookie。Cookie机制没有提供删除Cookie的方法,因此通过设置该Cookie即时失效实现删除Cookie的效果。失效的Cookie会被浏览器从Cookie文件或者内存中删除。

response对象提供的Cookie操作方法只有一个添加操作add(Cookie cookie)。要想修改Cookie只能使用一个同名的Cookie来覆盖原来的Cookie,达到修改的目的。删除时只需要把maxAge修改为0即可。

在所遇到的项目中,Action里创建了一个cookie,maxAge为-1,紧接着在另一个方法中要删除cookie,就可以通过创建一个同名同域的cookie,然后将maxAge设置为0,再通过response的addCookie方法对客户端的cookie文件或浏览器内存中的cookie进行删除。

注意一、修改、删除Cookie时,新建的Cookie除value、maxAge之外的所有属性,例如name、path、domain等,都要与原Cookie完全一样。否则,浏览器将视为两个不同的Cookie不予覆盖,导致修改、删除失败。

注意二、从客户端读取Cookie时,包括maxAge在内的其他属性都是不可读的,也不会被提交。浏览器提交Cookie时只会提交name与value属性。maxAge属性只被浏览器用来判断Cookie是否过期。

Cookie cookies[] = request.getCookies();

if (cookies != null)

{

for (int i = 0; i < cookies.length; i++)

{

if (cookies[i].getName().equalsIgnoreCase(cookieName))

{

return (Cookie) cookies[i].clone();

}

}

注意,这表示从request请求里获得cookie文件内容,只能获得name和value。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics