Cookie 可以用来将一些临时数据保存到浏览器中,比如你在浏览器的访问记录、登录密码、用户名等。
<br/>
**1. 对Cookie进行写、读、删操作**
```java
@WebServlet("/cookie")
public class CookieServlet extends BaseServlet {
/**
* 写Cookie
*/
public void write(HttpServletRequest request, HttpServletResponse response) {
//Cookie(String name, String value)
//name:cookie的名称
//value:cookie的值
Cookie cookie = new Cookie("user", "zhangsan");
//设置过期时间,如果不设置默认为-1,表示永不过期。单位s
cookie.setMaxAge(3600);
//通知浏览器保存Cookie
response.addCookie(cookie);
}
/**
* 读取Cookie
*/
public void read(HttpServletRequest request, HttpServletResponse response) throws IOException {
Cookie[] cookies = request.getCookies();
Map<String, Object> map = new HashMap<>(1);
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("user".equals(cookie.getName())) {
map.put(cookie.getName(), cookie.getValue());
}
}
}
response.getWriter().print(JSON.toJSONString(map));
}
/**
* 删除Cookie
*/
public void delete(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("user".equals(cookie.getName())) {
//设置过期时间为0即可删除
cookie.setMaxAge(0);
//通知浏览器更新cookie信息
response.addCookie(cookie);
}
}
}
}
}
```
**2. 测试**
```
访问:http://localhost:8080/web/cookie?method=write 写cookie
访问:http://localhost:8080/web/cookie?method=read 读cookie,将得到如下信息
{"user":"zhangsan"}
访问:http://localhost:8080/web/cookie?method=delete 删cookie,
然后再访问 http://localhost:8080/web/cookie?method=read 读cookie,会发现cookie已经不在了
```