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

你可能感兴趣的文章
-对wakanda靶机的渗透之旅
查看>>
every day a practice —— morning
查看>>
使用 Nmon 监控 Linux 的系统性能
查看>>
袋鼠云研发手记 | 开源·数栈-扩展FlinkSQL实现流与维表的join
查看>>
Character Sets: Migrating to utf8mb4 with pt_online_schema_change
查看>>
c++中typename和class的区别介绍
查看>>
[恢]hdu 2526
查看>>
程序员面试金典--取前K小的数
查看>>
study container
查看>>
图论及其应用——图的最短路径问题
查看>>
集合框架之Set HashSet
查看>>
@property@classmethod@staticmethod
查看>>
iOS chart 图表完美解决方案 基于swift
查看>>
【转载】API入门系列之三 -那迷惑人的Windows字符和字符指针类型
查看>>
Python标准库09 当前进程信息 (os包)
查看>>
【转】Unable to load native-hadoop library for your platform(已解决)
查看>>
HDU - 2159 FATE(二维dp之01背包问题)
查看>>
多个 additional include directories 的复制方法
查看>>
Java中 VO、 PO、DO、DTO、 BO、 QO、DAO、POJO的概念
查看>>
[COGS 2421] [HZOI 2016] 简单的Treap 笛卡尔树
查看>>