Skip to content
This repository has been archived by the owner on Aug 20, 2021. It is now read-only.

CookieUtil

feilong edited this page Jun 3, 2016 · 15 revisions

Cookie 工具类.

注意:该类创建Cookie仅支持Servlet3以上的版本

使用说明:

1:创建Cookie

1.1.创建一个name名字是shopName,value是feilong的 Cookie

(通常出于安全起见,存放到Cookie的值需要加密或者混淆,此处为了举例方便使用原码)

	CookieUtil.addCookie("shopName","feilong",response) 

注意:该方法创建的cookie,为会话Cookie,有效期是默认值 -1,即浏览器退出就删除

1.2.如果想给该cookie加个过期时间,有效期一天

如:

	CookieUtil.addCookie("shopName","feilong", TimeInterval.SECONDS_PER_DAY,response) 
1.3.如果还想给该cookie加上httpOnly等标识
	CookieEntity cookieEntity = new CookieEntity("shopName", "feilong", TimeInterval.SECONDS_PER_DAY);
	cookieEntity.setHttpOnly(true);
	CookieUtil.addCookie(cookieEntity, response);

此外,如果有特殊需求,还可以对cookieEntity设置 path,domain等属性


2:获取Cookie

2.1.获得 Cookie 对象
	CookieUtil.getCookie(request, "shopName") 
2.2.获得Cookie对象的字符串值
	CookieUtil.getCookieValue(request, "shopName") 

返回 feilong 字符串

3.获得所有的Cookie namevalue组成的map
	CookieUtil.getCookieMap(request) 

3:删除Cookie

3.1.删除名字是 shopName 的Cookie
	CookieUtil.deleteCookie(request, "shopName") 
3.2.删除有path路径的cookie

特殊时候,由于Cookie原先保存时候设置了path属性,那么我们需要如此这般

	CookieEntity cookieEntity = new CookieEntity("shopName", "feilong");
	cookieEntity.setPath("/member/account");
	CookieUtil.deleteCookie(request, "shopName");