在服务器段保存cookies的时候用的是response保存,假定此时的url为http://localhost/test.此时保存的cookie默认对test/下的目录有效,如果由于访问了默认的域名再通过request的forward转向下级目录的某个页面时候,此时无效。
以登录为例:默认访问的是http://localhost:8080/test这个web程序。
此时又以forward的方式转到http://localhost:8080/test/test1/login.jsp
当登录的时候处理保存cookie ,此时保存的就在http://localhost:8080/test/test1/下又效,
如果重新登录时http://localhost:8080/test ,获取不到cookie值,
而http://localhost:8080/test/test1/login.jsp 到登陆页面的时候就能获取到cookie的值
要是http://localhost:8080/test上级目录也有效,
解决方法可以设置根路径
Cookie c = new Cookie("username", URLEncoder.encode(user.getUsername()));
Cookie c1 = new Cookie("isAdmin", xform.getIsAdmin().toString());
c.setMaxAge(365*24*60*60);
c1.setMaxAge(365*24*60*60);
c.setPath("/");
c1.setPath("/");
response.addCookie(c);
response.addCookie(c1);