Cookie
利用cookie实现: 记录上次访问时间
response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<a href='ServletDemo/cookieDemo2'>删除上次访问时间</a>"); 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成功<br /><a href='ServletDemo/cookieDemo1'>返回</a>");
模拟浏览商品的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("本店有如下商品:<br />"); // 输出网站所有商品 Map<String, Book> map = DB.getAll(); for (Map.Entry<String, Book> entry : map.entrySet()) { Book book = entry.getValue(); out.write("<a href='ServletDemo/cookieDemo4?id=" + book.getId() + "'>" + book.getName() + "</a><br />"); } // 显示用户曾经浏览过的商品 out.write("<hr />"); out.write("你曾经浏览过的商品:<br />"); 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("<a href='ServletDemo/cookieDemo4?id=" + book.getId() + "' target='_blank'>" + book.getName() + "</a><br />"); } } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } //模拟数据库信息 class DB { private static Map<String, Book> 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("</br><a href='ServletDemo/cookieDemo3'>返回</a>"); // 构造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); } }