background image

Java 程序员:Cookie 的操作

  测试环境:JDK1.5、Tomcat5.5
  1.设置 Cookie
  1Cookie cookie = new Cookie("key", "value");
  2cookie.setMaxAge(60); //设置 60 秒生存期,如果设置为负值的话,则为浏览器
进程 Cookie(内存中保存),关闭浏览器就失效。
  3cookie.setPath("/test/test2"); //设置 Cookie 路径,不设置的话为当前路径(对
于 Servlet 来说为 request.getContextPath() + web.xml 里配置的该 Servlet 的 url-
pattern 路径部分)
  4response.addCookie(cookie);
  2.读取 Cookie
  11//

该方法可以读取当前路径以及 直接父路径 的所有 Cookie 对象,如果没有任何

Cookie 的话,则返回 null
  22Cookie[] cookies = request.getCookies();
  3.删除 Cookie
  1Cookie cookie = new Cookie("key", null);
  2cookie.setMaxAge(0); //设置为 0 为立即删除该 Cookie
  3cookie.setPath("/test/test2"); //删除指定路径上的 Cookie,不设置该路径,默
认为删除当前路径 Cookie
  4response.addCookie(cookie);
  4.注意:假设路径结构如下
  /
  /test
  /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 为/的