测试管理,自动化测试、手机客户端测试、wap站点测试研究

java操作cookie(转)

上一篇 / 下一篇  2011-07-13 18:07:23 / 个人分类:敏捷测试

1.设置Cookie51Testing软件测试网+t2|,z/i'L+Cp

YE4B%}b&Q7v4a;L.P Rn0Cookie cookie = new Cookie("key", "value");
a~4m| G0cookie.setMaxAge(60); //设置60秒生存期,如果设置为负值的话,则为浏览器进程Cookie(内存中保存),关闭浏览器就失效。51Testing软件测试网7c7mnL'v]V
cookie.setPath("/test/test2"); //设置Cookie路径,不设置的话为当前路径(对于Servlet来说为request.getContextPath() + web.xml里配置的该Servlet的url-pattern路径部分)51Testing软件测试网Jy&u3F.sp'n q
response.addCookie(cookie);
Q0mi7M z0
9u sVSSS{02.读取Cookie51Testing软件测试网0G&SH5m5H ?}zfQ

*v0lJnblX0该方法可以读取当前路径以及“直接父路径”的所有Cookie对象,如果没有任何Cookie的话,则返回null51Testing软件测试网\Ez'|9I ZM
Cookie[] cookies = request.getCookies();
nBAQ+gt+k051Testing软件测试网k e7t"nu#EN
3.删除Cookie
!d E-?,MZ#DFf AO Y0
E8p Fp9E0Cookie cookie = new Cookie("key", null);51Testing软件测试网d@V}3B%E
cookie.setMaxAge(0); //设置为0为立即删除该Cookie51Testing软件测试网8TxR6a eJ5n
cookie.setPath("/test/test2"); //删除指定路径上的Cookie,不设置该路径,默认为删除当前路径Cookie51Testing软件测试网 GL;l"X;V
response.addCookie(cookie);
@:]i~&H/s0
_M!z}9gmy04.修改Cookie
_ uR)K-D6H q0首先读取cookie
Y| }'s5{:k,j0Cookie[] cks = request.getCookies();51Testing软件测试网2B!ak {7?+y-YQ N0Fv0y
for (int i = 0; i < cks.length; i ++){
)L"u0Z%u%Nfm+PCq9i7^l|0  Cookie cookie = cks[i];51Testing软件测试网i%T}D)Z!E2B
  if (cookie.getName().equalsIgnoreCase("cookiename")){51Testing软件测试网B:}[w [+b%l
cookie.setValue("newvalue"); 设置新的值
u g:pEu I!T0        response.addCookie(cookie);51Testing软件测试网;f1W W$rJ/_!myH
   }51Testing软件测试网BX CpYE
}
1YVI t'H;q051Testing软件测试网*R6?#@!gtO+W\
5.注意:假设路径结构如下51Testing软件测试网VA z+e q5iT(Hi

*iF FY:HJM+oN A,G qG0/
,h+qMuP]\u0
t+Y O+Xb.O)t`0/test
wr&aE#~ B@0
I v#c!jP$Q9eM^0/test/test251Testing软件测试网J9kp O,]3HSd^ C
51Testing软件测试网6~YI:S }*l
/test34551Testing软件测试网7U(F)LV;AB
51Testing软件测试网*?HO2B*z5b8Z]8R
/test555/test666
R#J8C"s7a$Y&k \p051Testing软件测试网N6W&ar4r*^Ksyc?
a.相同键名的Cookie(值可以相同或不同)可以存在于不同的路径下。51Testing软件测试网scT"zUw.om

{6^.f$?W?%l0b. 删除时,如果当前路径下没有键为"key"的Cookie,则查询全部父路径,检索到就执行删除操作(每次只能删除一个与自己最近的父路径Cookie)
?X`$r$H\0
3l8Ni.Nk cW6A:w0FF.必须指定与设定cookie时使用的相同路径来删除改cookie,而且cookie的键名不论大写、小写或大小混合都要指定路径。51Testing软件测试网4R)f#kj G:^

LQLa!u(]L&R{%?Z%t0IE.键名小写时,如果当前路径为/test/test2,如果找不到再向上查询/test、/test555、/test345,如果还找不到就查询/ 。(/test555/test666不查询)
3zJ.B.u)SYXi051Testing软件测试网 w7N/Hh-[ A2G
键名大小写混合或大写时,不指定路径则默认删除当前路径,并且不向上查询。
YUKQD ?i0
cu,E5sf G,u7m0c.读取Cookie时只能读取直接父路径的Cookie。
l&C#Y m2x0
V3ti1T|`'rMC[r0如果当前路径为/test/test2,要读取的键为"key"。当前路径读取后,还要读取/test,/test读取后,还要读取/51Testing软件测试网 f4M1j`?
51Testing软件测试网6L7} B G oP ^}
d.在做Java的web项目时,由于一般的Web服务器(如Tomcat或Jetty)都用Context来管理不同的Web Application,这样对于每个Context有不同的Path,
tp\)PD8Db4L0
qWG,v&g+NUp0在一个Server中有多个Web Application时要特别小心,不要设置Path为/的Cookie,容易误操作。(当然前提是域名相同)

TAG:

 

评分:0

我来说两句

Open Toolbar