1.设置Cookie
Cookie cookie =
Cookie("key", "value");
cookie.
MaxAge(60);
设置60秒生存期
如果设置为负值
话
则为浏览器进程Cookie(内存中保存)
关闭浏览器就失效
cookie.
Path("/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 =
Cookie("key", null);
cookie.
MaxAge(0);
设置为0为立即删除该Cookie
cookie.
Path("/test/test2");
删除指定路径上
Cookie
不设置该路径
默认为删除当前路径Cookie
response.addCookie(cookie);
4.注意:假设路径结构如下
test/test2/test345/test555/test666
a.相同键名
Cookie(值可以相同或区别)可以存在于区别
路径下
b. 删除时
如果当前路径下没有键为"key"
Cookie
则查询全部父路径
检索到就执行删除操作(每次只能删除
个和自己最近
父路径Cookie)
FF.必须指定和设定cookie时使用
相同路径来删除改cookie
而且cookie
键名不论大写、小写或大小混合都要指定路径
IE.键名小写时
如果当前路径为/test/test2
如果找不到再向上查询/test、/test555、/test345
如果还找不到就查询/
(/test555/test666不查询)
键名大小写混合或大写时
不指定路径则默认删除当前路径
并且不向上查询
c.读取Cookie时只能读取直接父路径
Cookie
如果当前路径为/test/test2
要读取
键为"key"
当前路径读取后
还要读取/test
/test读取后
还要读取/
d.在做Java
web项目时
由于
般
Web服务器(如Tomcat或Jetty)都用Context来管理区别
Web Application
这样对于每个Context有区别
Path
在
个Server中有多个Web Application时要特别小心
不要设置Path为/
Cookie
容易误操作
(当然前提是域名相同)
延伸阅读
最新评论