0%

【JavaWeb】Cookie

Cookie介绍和学习


1 Cookie介绍

  • Cookie直译为饼干
  • Cookie是服务器通知客户端保存键值对的一种技术
  • 客户端有了Cookie之后,每次请求都会携带Cookie发送给服务端
  • 每个Cookie的大小不能超过4KB

2 Cookie创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 创建Cookie
* @param req
* @param resp
*/
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建cookie
Cookie cookie = new Cookie("key1", "value1");
// 通知客户端保存cookie
resp.addCookie(cookie);
// 支持添加多个cookie
Cookie cookie2 = new Cookie("key2", "value2");
resp.addCookie(cookie2);
}

3 Cookie获取

1
2
3
4
5
6
7
8
9
/** 获取Cookie */
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取Cookie
Cookie[] cookies = req.getCookies();
// 遍历
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + "=" + cookie.getValue());
}
}

4 Cookie存活

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/** 设置Cookie存活 */
protected void liftCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置cookie存活时间(正数、单位秒)
Cookie cookie1 = new Cookie("age", "60");
cookie1.setMaxAge(60);
resp.addCookie(cookie1);
// 删除cookie(0)
Cookie cookie2 = new Cookie("age", "0");
cookie2.setMaxAge(0);
resp.addCookie(cookie2);
// 浏览器关闭,清除cookie(负数,默认)
Cookie cookie3 = new Cookie("age", "-1");
cookie3.setMaxAge(-1);
resp.addCookie(cookie3);
}

5 Cookie过滤

  • 可以通过cookie的path属性,来过滤cookie的发送
  • path属性会跟请求地址进行匹配,匹配成功才将cookie添加进请求头中