文章目录
Cookie
1.创建Cookie对象
Cookie cookie = new Cookie("key1", "value1");
2.保存Cookis对象, 通知客户端保存Cookie对象
resp.addCookie(cookie);
3.查询cookie值
public static Cookie findCookie(Cookie[] cookies, String key) {
if (cookies == null || cookies.length == 0 || key == null){
return null;
}
for (Cookie cookie : cookies) {
if (key.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
4. 得到cookie集合
Cookie[] cookies = req.getCookies();
5. 修改cookie值
//方案一:直接创建一个同键的cookie对象,并添加即可
Cookie cookie = new Cookie("key1","newValue1");
resp.addCookie(cookie);
//方案二:用查找工具找到要修改的cookie的值,用setValue修改,并添加
Cookie cookie = CookieUtil.findCookie(req.getCookies(), "key11");
if (cookie != null) {
cookie.setValue("newValue11");
resp.addCookie(cookie);
}
6. 设置cookie生命周期
cookie.setMaxAge();
//正数:存活时间单位"秒"
//负数:直到浏览器关闭
//0:马上关闭
//删除指定cookie
Cookie cookie = CookieUtil.findCookie(req.getCookies(),"key11");//先找到目的cookie
cookie.setMaxAge(0);
resp.addCookie(cookie);
7. cookie的path属性
//用于过滤特殊path的cookie对象
//设置cookie的path属性
cookie.setPath(req.getContextPath()+"/abc");
/**
当网址访问到工程名的路径时(http://localhost:8088/工程名),
其他的path属性(http://localhost:8088/工程名/abc)访问不到,
即创建不了cookie对象
*/
当path为(http://localhost:8088/工程名)时,
上图的(http://localhost:8088/工程名/abc)被过滤掉了
8. El表达式
value="${cookie.username.value}"
//前端通过EL表达式,获取cookie对象的value值