1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建cookie(name, value)
Cookie cookie = new Cookie("username","admin");
// 设置cookie生命周期(如果没有设置,则关闭浏览器cookie消失)
cookie.setMaxAge(3200);
// 把cookie信息回写个浏览器
response.addCookie(cookie);

// 读取cookie
// 获取所有cookie
Cookie cookies[] = new request.getCookies();
// 筛选
for(int i = 0; i < cookies.length; i++){
Cookie cookie = cookies[i];
}
1
2
3
4
String username = java.net.URLEncoder.encode("刘云龙","UTF-8");
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(3200);
response.addCookie(cookie);
1
String username = java.net.URLDecoder.decode(cookie.getValue(),"UTF-8");
  1. 如果 cookie 重名了,会被替换
  2. cookie 是明文存放,得加密存放

Cookie 案例:提示用户上次登录时间