设置Cookie

1.设置Cookie

  1 Cookie cookie = new Cookie("key", "value");

  2 cookie.setMaxAge(60); //设置60秒生存期,如果设置为负值的话,则为浏览器进程Cookie(内存中保存),关闭浏览器就失效。

  3 getPath/setPath获取/设置Cookie适用的路径。如果不指定路径,Cookie将返回给当前页面所在目录及其子目录下的所有页面。这里的方法可以用来设定一些更一般的条件。例如,someCookie.setPath("/"),此时服务器上的所有页面都可以接收到该Cookie。

  4 response.addCookie(cookie);

  2.读取Cookie

  1 1//该方法可以读取当前路径以及“直接父路径”的所有Cookie对象,如果没有任何Cookie的话,则返回null

  2 2Cookie[] cookies = request.getCookies();

  3.删除Cookie

  1 Cookie cookie = new Cookie("key", null);

  2 cookie.setMaxAge(0); //设置为0为立即删除该Cookie

  3 cookie.setPath("/test/test2"); //删除指定路径上的Cookie,不设置该路径,默认为删除当前路径Cookie

  4 response.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为/的Cookie,容易误操作。(当然前提是域名相同)

示例:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie cookies[] = request.getCookies();
if (cookies == null || name == null || name.length() == 0) {
return null;
}
for (int i = 0; i < cookies.length; i++) {
if (name.equals(cookies[i].getName())
&& request.getServerName().equals(cookies[i].getDomain())) {
return cookies[i];
}
}
return null;
}

public static void deleteCookie(HttpServletRequest request,
HttpServletResponse response, Cookie cookie) {
if (cookie != null) {
cookie.setPath(getPath(request));
cookie.setValue("");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}

public static void setCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value) {
setCookie(request, response, name, value, 0x278d00);
}

public static void setCookie(HttpServletRequest request,
HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value == null ? "" : value);
cookie.setMaxAge(maxAge);
cookie.setPath(getPath(request));
response.addCookie(cookie);
}

private static String getPath(HttpServletRequest request) {
String path = request.getContextPath();
return (path == null || path.length()==0) ? "/" : path;
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值