博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
lock_sga引起的ksvcreate :process(m000) creation failed
查看>>
面向抽象/接口编程以及继承
查看>>
POJ 1704 Georgia and Bob
查看>>
数据库插入数据乱码问题
查看>>
Jquery属性获取——attr()与prop()
查看>>
OVER(PARTITION BY)函数用法
查看>>
uva-11995 - I Can Guess the Data Structure!(栈,优先队列,队列,水题)
查看>>
webpack-dev-server 的服务无法使用的问题
查看>>
day11
查看>>
Collections -- 集合的工具类
查看>>
我组第二次全体会议顺利召开!
查看>>
ideat使用struts2之自定义MVC框架
查看>>
排序_选择排序
查看>>
altium annotate 选项设置 complete existing packages
查看>>
前端的md5加密
查看>>
Effective java 系列之异常转译
查看>>
2018年开局第一场“风口”---区块链,最致命的5个坑。
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>