1. Cookie饼干
1.1 什么是Cookie
- Cookie是服务器通知客户端保存键值对的一种技术
- 客户端有了Cookie后,每次请求都发送给服务器
- 每个cookie大小不能超过4kb
1.2 cookie的创建
![cookie](https://img-blog.csdnimg.cn/20210320162639583.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQyMTUxMzE=,size_16,color_FFFFFF,t_70)
public class CookieServlet extends BaseServlet {
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie1 = new Cookie("key1", "value1");
Cookie cookie2 = new Cookie("name", "gau");
resp.addCookie(cookie1);
resp.addCookie(cookie2);
resp.getWriter().write("cooke创建成功");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
1.3 服务器如何获取cookie
- 服务器获取客户端的cookie只需要一行代码req.getCookies().Cookie[]
![获取cookie](https://img-blog.csdnimg.cn/20210320183937821.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQyMTUxMzE=,size_16,color_FFFFFF,t_70)
public class CoolieUtils {
public static Cookie findCookie(String name, Cookie[] cookies) {
if (name == null || cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
Cookie iWantCoolie = CoolieUtils.findCookie("name", cookies);