博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cookie
阅读量:4681 次
发布时间:2019-06-09

本文共 7195 字,大约阅读时间需要 23 分钟。

Cookie

利用cookie实现: 记录上次访问时间

response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.print("删除上次访问时间");        out.print("您上次的访问时间是:");        // 获得用户的访问时间cookie        Cookie cookies[] = request.getCookies();        for (int i = 0; cookies != null && i < cookies.length; i++) {            if (cookies[i].getName().equals("lastAccessTime")) {                long value = Long.parseLong(cookies[i].getValue());                Date date = new Date(value);                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                out.write(format.format(date));            }        }        // 给用户回送最新的访问时间        Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()                + "");        cookie.setMaxAge(3600 * 24 * 365);// 设置保存时间是以秒为单位,这里是设置保存大约1年        cookie.setPath("ServletDemo");        response.addCookie(cookie);

 

删除Cookie

Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");        cookie.setPath("ServletDemo");//原先cookie的存储路径一定要一致        cookie.setMaxAge(0);//设置Cookie存活时间为0,关闭浏览器后,session将会被清楚
response.addCookie(cookie); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.getWriter().write("删除cookie成功
返回");

 

模拟浏览商品的Servlet
/** * 模拟浏览商品 */@WebServlet("/cookieDemo3")public class CookieDemo3 extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        response.setCharacterEncoding("UTF-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.write("本店有如下商品:
"); // 输出网站所有商品 Map
map = DB.getAll(); for (Map.Entry
entry : map.entrySet()) { Book book = entry.getValue(); out.write("
" + book.getName() + "
"); } // 显示用户曾经浏览过的商品 out.write("

"); out.write("你曾经浏览过的商品:
"); Cookie cookie[] = request.getCookies(); for (int i = 0; cookie != null && i < cookie.length; i++) { if (cookie[i].getName().equals("bookHistory") && cookie[i].getValue() != null) { String ids[] = cookie[i].getValue().split("\\,"); for (String id : ids) { Book book = map.get(id); out.write("
" + book.getName() + "
"); } } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}//模拟数据库信息class DB { private static Map
map = new LinkedHashMap(); static { map.put("1", new Book("1", "java", "1,java")); map.put("2", new Book("2", "html", "1,html")); map.put("3", new Book("3", "css", "1,css")); map.put("4", new Book("4", "javascript", "1,javascript")); map.put("5", new Book("5", "xml", "1,xml")); map.put("6", new Book("6", "jsp", "1,jsp")); } public static Map getAll() { return map; }} class Book { public Book() { } public Book(String id, String name, String description) { super(); this.id = id; this.name = name; this.description = description; }   private String id; private String name; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }}

 

模拟展示商品详细信息的Servlet

 

/* * 模拟展示商品详细信息的Servlet * */@WebServlet("/cookieDemo4")public class CookieDemo4 extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        String id = request.getParameter("id");        Book book = (Book) DB.getAll().get(id);        out.write(book.getName() + ":" + book.getDescription());        out.write("
返回"); // 构造Cookie 返回给浏览器 String cookValue = buildCookieValue(id, request); Cookie cookie = new Cookie("bookHistory", cookValue); cookie.setMaxAge(3600 * 24 * 30);// 设置cookie保存时间为一个月 cookie.setPath("ServletDemo"); response.addCookie(cookie); } // 构造CookieValue private String buildCookieValue(String id, HttpServletRequest request) { /* * 分析Cookie中可能存在的bookHistory * 已存在值 将要插入值      *  bookHistory=null 1 情况1 * bookHistory=2,3,1 1 情况2 * bookHistory=2,4,5 1 情况3 * bookHistory=2,3 1 情况4 */ String bookHistory = null; Cookie cookie[] = request.getCookies(); for (int i = 0; cookie != null && i < cookie.length; i++) { if (cookie[i].getName().equals("bookHistory")) { bookHistory = cookie[i].getValue(); if (bookHistory == null) { //情况1 return id; } LinkedList list = new LinkedList(Arrays.asList(bookHistory.split("\\,")));         //简化代码后 if (list.contains(id)) { //情况2 list.remove(id); } else { if (list.size() >= 3) { //情况3 list.removeLast(); } }          //情况4 list.addFirst(id); StringBuffer sb = new StringBuffer(); for (Object ids : list) { sb.append(ids.toString() + ","); } return sb.deleteCharAt(sb.length() - 1).toString(); // 简化代码前 /* * if (list.contains(id)) { // bookHistory=2,3,1 1 * list.remove(id); * list.addFirst(id); * } else {
* if (list.size()>= 4) {// bookHistory=2,4,5 1 * list.removeLast(); * list.addFirst(id); * } else { // bookHistory= 2,3 1 * list.addFirst(id); * }           *  } */ } } return null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}

 

转载于:https://www.cnblogs.com/lhy_2011/p/4044819.html

你可能感兴趣的文章
常用的匹配正则表达式和实例
查看>>
小组成员及其git链接
查看>>
SQL case when else
查看>>
MVc Identity登陆锁定
查看>>
cdn连接失败是什么意思_关于CDN的原理、术语和应用场景那些事
查看>>
ultraedit26 运行的是试用模式_免费试用U盘数据恢复工具 – 轻松找回U盘丢失的各种数据!...
查看>>
plsql 查询存储过程死锁语句_插入语句/存储过程死锁
查看>>
bootstrap table 收缩_bootstrap-table方法之:expandRow-collapseRow,展开或关闭当前行数据...
查看>>
jsp跳转到本身页面_五种JSP页面跳转方法详解
查看>>
mysql r_mysql:’r’是什么意思?
查看>>
无法加载 mysql 扩展_请检查您的 php 配置. - 文档_无法载入 mysql 扩展 请检查 PHP 配置...
查看>>
非空 默认 男 mysql_MySQL进阶13--常见六大约束: 非空/默认/主键/唯一约束/检查约束/外键约束--表级约束 / 列级约束...
查看>>
mysql错误修改数据_mysql数据修改问题
查看>>
navicat忘记mysql密码_navicat连接My SQL时忘记root密码处理方法
查看>>
mysql 左连接 左外连接吗_什么是左外连接?左外连接在工作表查询中的应用
查看>>
python sum函数导入list_python sum函数iterable参数为二维list,start参数为“[]”该如何理解...
查看>>
docker 删除多余镜像_多余Basedisk删除和vDisk镜像反转技术简介
查看>>
mysqlin会使用索引吗_被面试官虐了,索引为何使用B+树,你知道吗
查看>>
mysql8单节点500m_Kubernetes 部署 Mysql 8.0 数据库(单节点)
查看>>
mysql数据工厂生产_MySQL超时与天蓝色数据工厂副本
查看>>