01_Cookie的介绍
- 概念
- 网景公司发明。是浏览器的会话技术
- Cookie的流程
- 浏览器请求服务器,请求Demo01Servlet,创建一个Cookie对象,名称为cookie1
- 可以通过响应头Set-Cookie,携带cookie给浏览器进行保存
- 浏览器再次请求服务器,请求Demo02Servlet,获取cookie1对象
02_Cookie的基本使用
-
设置Cookie
-
方式一(不推荐)
response.addHeader("set-cookie","msg=hellocoolie");
-
方式二(推荐)
Cookie cookie = new Cookie("msg","hellocookie"); response.addCookie(cookie);
-
-
获取Cookie
-
开发步骤
- 通过request对象获取所有的Cookie对象,存储到一个数组中
- 遍历该数组,匹配Cookie名称
- 如果匹配上,就知道了指定的Cookie对象
- 如果匹配不上,就没有指定的Cookie对象
-
代码实现
Cookie[] cookies = request.getCookies(); Cookie cookie = null; for(Cookie sonCookie : cookies){ if("msg".equals(sonCookie.getName())){ cookie = sonCookie; } } if(null != cookie){ System.out.println("name : "+msgCookie.getName() + " , value : "+ msgCookie.getValue()); }
-
03_Cookie的相关设置
-
持久化设置
- cookie的生命周期
- 默认是随着浏览器的关闭而销毁
- setMaxAge
- 设置cookie的存活时长,cookie就可以不随着会话的关闭而销毁!
- cookie的生命周期
-
路径设置
-
默认情况下,Cookie对象会随着任何一个请求携带到服务器
-
setPath
- 设置Cookie的访问路径
Cookie cookie = new Cookie("msg","helloworld"); cookie.setPath("/day56/demo04"); response.addCookie(cookie);
- cookie对象只有访问路径包含"/day56/demo04",才会跟随请求携带到服务器
-
04_Cookie案例之记录上一次访问时间
-
需求:
- 第一次访问,就直接打印当前时间
- 不是第一次访问,就打印上一次的访问时间
-
开发步骤
- 获取对应的Cookie对象
- 判断是否是第一次访问
- 如果是第一次访问
- 打印当前时间
- 将当前时间存储到Cookie中
- 如果不是第一次访问
- 打印上一次访问时间
- 将当前时间存储到Cookie中
-
代码实现
//判断是否是一次请求 Cookie[] cookies = request.getCookies(); Cookie cookie = null;//记录上一次的访问时间 if (cookies != null && cookies.length != 0 ) { for (Cookie sonCookie : cookies) { if ("lastTime".equals(sonCookie.getName())) { cookie = sonCookie; //拿到lastTime } } } SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss"); if (null == cookie) { //第一次访问 ,打印当前时间,并将创建Cookie对象,存储当前时间 Date currentDate = new Date(); System.out.println("第一次访问,时间为" + format.format(currentDate)); cookie = new Cookie("lastTime",currentDate.getTime()+""); } else { //不是第一次访问,从cookie取出上一次的访问时间,并打印。获取当前时间,并存储cookie对象中 long lastDateMills = Long.parseLong(cookie.getValue()); Date lastDate = new Date(lastDateMills); //获取到了上一次的访问时间 String lastTimeStr = format.format(lastDate); System.out.println("上一次访问,时间为" + lastTimeStr); //获取当前时间,并存储cookie对象中 Date currentDate = new Date(); // cookie.setValue(currentDate.getTime()+""); cookie = new Cookie("lastTime",currentDate.getTime()+""); } response.addCookie(cookie); //放回cookie
05_Cookie案例之商品浏览记录
-
需求
- 浏览商品,将商品的浏览的记录起来,并显示!
-
开发步骤
- 获取history的Cookie对象
- 判断商品浏览记录是否为空
- 如果浏览记录没有
- 创建Cookie,并将当前的商品记录到Cookie中
- 如果浏览记录有
- 有当前的商品,不做任何处理
- 没有当前商品,就需要将当前的商品拼接到已有记录中
-
代码实现
- 页面代码
<a href="/day56/history?id=0">西游记</a><br> <a href="/day56/history?id=1">红楼梦</a><br> <a href="/day56/history?id=2">水浒传</a><br> <a href="/day56/history?id=3">三国志</a><br>
- 商品浏览记录
//拿到id的值。通过queryString的方式传递 String id = request.getParameter("id"); Cookie cookie = null; Cookie[] cookies = request.getCookies(); if (null != cookies && 0 != cookies.length){ for (Cookie sonCookie : cookies) { if ("history".equals(sonCookie.getName())) { cookie = sonCookie; } } } if (null == cookie) { //之前没有任何浏览记录 ,创建Cookie对象 ,并存储浏览记录(id) cookie = new Cookie("history",id); } else { //之前有一些浏览记录 String historyStr = cookie.getValue(); if (!historyStr.contains(id)) { //有一些记录,但是不包含当前浏览的商品; //将浏览商品拼接到已有浏览记录中 //120 //1-2-0 historyStr += "-"+id; cookie.setValue(historyStr); } else { //有一些记录,包含当前浏览的商品 ,不做任何处理 } } response.addCookie(cookie); //上述代码,已经完成了商品浏览记录功能,剩下就是要显示商品浏览记录 response.sendRedirect(request.getContextPath()+ File.separator+"showHistory");
- 显示商品浏览记录
- 获取history对应的Cookie对象
- 获取对应的商品浏览记录
- 判断是否有浏览记录
- 如果没有,就显示“没有浏览记录”
- 如果有,就显示
- 处理浏览记录字符串
Cookie cookie = null; Cookie[] cookies = request.getCookies(); if (null != cookies && 0 != cookies.length) { for (Cookie sonCookie : cookies) { if ("history".equals(sonCookie.getName())) { cookie = sonCookie; } } } StringBuffer responseContent = new StringBuffer();//记录响应正文 if (null == cookie) { //没有浏览记录 responseContent.append("<font color='red'>没有浏览记录</font>,"); responseContent.append("<a href='books.html'>浏览商品</a>"); } else { //有浏览记录 //获取浏览记录 0-1-2-3 String[] bookNames = {"西游记","红楼梦","水浒传","三国志"}; String historyStr = cookie.getValue(); String[] historys = historyStr.split("-"); responseContent.append("您的浏览记录如下:<br>"); for (String history : historys) { //history : 0 / 1 / 2 /3 String bookName = bookNames[Integer.parseInt(history)]; responseContent.append(bookName+"<br>"); } } response.setContentType("text/html;charset=utf-8"); 写回网页 response.getWriter().write(responseContent.toString());
06_CookieUtils工具类
- 获取指定名称的Cookie对象
public static Cookie getCookie(Cookie[] cookies ,String cookieName){
if (null != cookies && 0 != cookies.length) {
for (Cookie sonCookie : cookies) {
if (cookieName.equals(sonCookie.getName())) {
return sonCookie;
}
}
}
return null;
}