1. 程式人生 > >【轉】JAVA中Cookie MaxAge屬性及其使用

【轉】JAVA中Cookie MaxAge屬性及其使用

轉自:http://hi.baidu.com/suofang/item/06ea24ba63a7dceb4fc7fd17

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。