Cookie
尚硅谷学习笔记
什么是Cookie?
- Cookie是服务器通知客户端保存键值对的一种技术。
- 客户端有了 Cookie 后,每次请求都发送给服务器。
- **每个 Cookie 的大小不能超过 4kb **
如何创建Cookie
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 创建Cookie对象
Cookie cookie = new Cookie("name","Veneno");
// 2. 通知客户端加入Cookie对象
resp.addCookie(cookie);
// 1. 创建Cookie对象,可以创建多个
Cookie cookie1 = new Cookie("name1","Veneno1");
// 2. 通知客户端加入Cookie对象
resp.addCookie(cookie1);
}
服务器端如何获取Cookie
服务器端获取Cookie只需要使用req.getCookies():Cookie[]方法。
因为开发过程中,一般只需要指定的Cookie对象,所以我们可以把查找指定Cookie对象的方法写成一个工具类
Cookie的工具类
/*
* @des 通过Cookie名搜索指定Cookie对象
* @params [name, cookies]
* @return javax.servlet.http.Cookie
**/
public static Cookie findCookieByName(String name,Cookie[] cookies) {
if (name == null || cookies == null || cookies.length==0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())