Cookie cookie = new Cookie("key", "value");
cookie.setMaxAge(60);
設(shè)置60秒生存期,如果設(shè)置為負(fù)值的話,則為瀏覽器進(jìn)程Cookie(內(nèi)存中保存),關(guān)閉瀏覽器就失效。
cookie.setPath("/test/test2");
設(shè)置Cookie路徑,不設(shè)置的話為當(dāng)前路徑(對(duì)于Servlet來說為request.getContextPath() + web.xml里配置的該Servlet的url-pattern路徑部分)
response.addCookie(cookie);
2.讀取Cookie
該方法可以讀取當(dāng)前路徑以及“直接父路徑”的所有Cookie對(duì)象,如果沒有任何Cookie的話,則返回null
Cookie[] cookies = request.getCookies();
3.刪除Cookie
Cookie cookie = new Cookie("key", null);
cookie.setMaxAge(0);
設(shè)置為0為立即刪除該Cookie
cookie.setPath("/test/test2");
刪除指定路徑上的Cookie,不設(shè)置該路徑,默認(rèn)為刪除當(dāng)前路徑Cookie
response.addCookie(cookie);
4.修改Cookie
Cookie[] cookies=request.getCookies();
if(cookies.length>1){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("key")) {
String oldValue = cookies[i].getValue();
String newValue= "newValue";
cookies[i].setValue(newValue);
response.addCookie(cookies[i]);
break;
}
}
}
名稱: ?4C.ESL | .↗Evon
口號(hào): 遇到新問題?先要尋找一個(gè)方案乄而不是創(chuàng)造一個(gè)方案こ
mail: 聯(lián)系我