什么是cookie?
- Cookie是服务器通知客户端保存键值对的一种技术
- 客户端有了Cookie之后,每次请求头发送给服务器
- 每个Cookie的大小不能超过4kb
一次可以创建多个Cookie
服务端获取客户端的Cookie
public class CookieServlet extends HttpServlet {
protected void GetCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
Cookie iWant=null;
for (Cookie cookie:cookies){
resp.getWriter().write(cookie.getName()+"+"+cookie.getValue());
if("key2".equals(cookie.getName())){
iWant=cookie;
}
}
for (Cookie cookie:cookies){
if("key2".equals(cookie.getName())){
iWant=cookie;
break;
}
}
if(iWant!=null){
resp.getWriter().write("找到了需要的cookie");
}
}
}
编写获取Cookie的工具类:
public class CookieUtils {
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;
}
}
Cookie 值的修改
方案一:
- 先创建一个要修改的同名的Cookie对象
- 在构造器,同时赋予新的Cookie值
- 调用response.addCookie(cookie);
public class UpdateCookie extends HttpServlet {
protected void doCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.先创建一个要修改的同名的Cookie对象
//2.在构造器,同时赋予新的Cookie值
Cookie cookie = new Cookie("key1", "newValue1");
//3.调用response.addCookie(cookie);通知客户端保存修改
resp.addCookie(cookie);
resp.getWriter().write("key1的值已经修改");
}
}
方案二:
- 先查找需要修改的Cookie对象
- 调用setValue()方法赋予新的cookie值
3.调用resoponse.addCookie() 通知
protected void cookieUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie= CookieUtils.findCookie("key2",req.getCookies());
if(cookie!=null){
cookie.setValue("newValue2");
}
resp.addCookie(cookie);
}
Cookie的生命控制
Cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)
setMaxAge()
正数,表示在指定的秒数后过期
Cookie cookie1 = new Cookie("life3600","life3600");
cookie1.setMaxAge(60*60);//一小时之后删除
resp.addCookie(cookie1);
负数,表示浏览器一关,Cookie就会被删除(默认值-1)
零,表示马上删除Cookie
Cookie有效路径Path的设置
Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器,哪些不发。
path属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径
Cookie path=/工程路径/abc
请求地址如下:
http://ip:port/工程路径/a.html
CookieA发送
CookieB不发送
http://ip:port/工程路径/abc/a.html
CookieA发送
CookieB发送
Cookie cookie2 = new Cookie("path1","path1");
cookie.setPath(req.getContextPath()+"/abc");//工程路径/abc