1.設定Cookie
Cookie cookie = new Cookie("key", "value");
cookie.setMaxAge(60);
設定60秒生存期,如果設定為負值的話,則為浏覽器程序Cookie(記憶體中儲存),關閉浏覽器就失效。
cookie.setPath("/test/test2");
設定Cookie路徑,不設定的話為目前路徑(對于Servlet來說為request.getContextPath() + web.xml裡配置的該Servlet的url-pattern路徑部分)
response.addCookie(cookie);
2.讀取Cookie
該方法可以讀取目前路徑以及“直接父路徑”的所有Cookie對象,如果沒有任何Cookie的話,則傳回null
Cookie[] cookies = request.getCookies();
3.删除Cookie
Cookie cookie = new Cookie("key", null);
cookie.setMaxAge(0);
設定為0為立即删除該Cookie
cookie.setPath("/test/test2");
删除指定路徑上的Cookie,不設定該路徑,預設為删除目前路徑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;
}
}
}