Cookie
会话:
保存会话数据的两种技术:
Cookie技术:
Session技术:
Cookie API:
Cookie应用:
Servlet代码:
//代表网站首页 public class CookieDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type","text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("<a href='/day07/servlet/CookieDemo2'>清除上次访问时间</a></br>"); out.print("您上次访问时间是:"); //获得用户的时间cookie Cookie cookies[] = request.getCookies(); for(int i = 0 ; cookies!=null&&i<cookies.length;i++){ if(cookies[i].getName().equals("lastAccessTime")){ long cookieValue = Long.parseLong(cookies[i].getValue()); //得到用户上次访问时间(转成long类型,即毫秒值) Date date = new Date(cookieValue); out.print(date.toLocaleString()); } } //给用户回送最新的访问时间 Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(1*30*24*3600); //设置cookie有效时间为1个月 cookie.setPath("/day07"); //设置cookie有效路径 response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
public class CookieDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //要想清除cookie,则setMaxAge(0),而且其他属性必须一致,比如path Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(0); cookie.setPath("/day07"); response.addCookie(cookie); response.setStatus(302); response.setHeader("Location", "/day07/servlet/CookieDemo1"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }Cookie细节:
![](http://img-my.csdn.net/uploads/201304/24/1366793435_3333.png)
Cookie案例—显示商品浏览记录:
Servlet代码:
//商品类(书籍) class Book{ private String id; private String name; private String author; private String description; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, String description) { super(); this.id = id; this.name = name; this.author = author; this.description = 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 getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
//数据库(如果有检索数据需求,则用双列(Map),如果不检索,则用单列(List) ) class Db{ private static Map<String,Book> map = new LinkedHashMap(); //如果用HashMap,则获取商品顺序和存入顺序不一致,hashMap是根据hash值排列的 //静态块,一使用Db类就自动执行 static{ map.put("1", new Book("1","javaweb开发","老张","一本好书")); map.put("2", new Book("2","jdbc开发","老张","一本好书")); map.put("3", new Book("3","spring开发","老黎","一本好书")); map.put("4", new Book("4","struts开发","老毕","一本好书")); map.put("5", new Book("5","android开发","老黎","一本好书")); } public static Map getAll(){ return map; } }
//代表首页的servlet public class CookieDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //1.输出网站所有商品 out.write("本网站有如下商品:<br/>"); Map<String, Book> map = Db.getAll(); //1.迭代map要把map先用entrySet方法转成Set //2.用增强for循环对map迭代,迭代出的每一个都是Map.Entry for(Map.Entry<String, Book> entry : map.entrySet()){ Book book = entry.getValue(); out.print("<a href='/day07/servlet/CookieDemo4?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>"); } //2.显示用户曾经看过的商品 out.print("<br/>您曾经看过如下商品:<br/>"); Cookie cookies[] = request.getCookies(); for(int i = 0;cookies!=null&&i<cookies.length;i++){ if(cookies[i].getName().equals("bookHistory")){ String ids[] = cookies[i].getValue().split("\\,"); //用逗号分割,用\\转义,确保不出问题 for(String id : ids){ Book book = (Book)Db.getAll().get(id); out.print(book.getName()+"<br/>"); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//显示商品详细信息的servlet public class CookieDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //1.根据用户带过来的id,显示响应商品的详细信息 String id = request.getParameter("id"); Book book = (Book)Db.getAll().get(id); out.write(book.getId()+"<br/>"); out.write(book.getAuthor()+"<br/>"); out.write(book.getName()+"<br/>"); out.write(book.getDescription()+"<br/>"); //2.构建cookie,回写给浏览器 String cookieValue = buildCookie(id,request); Cookie cookie = new Cookie("bookHistory",cookieValue); cookie.setMaxAge(1*30*24*3600); cookie.setPath("/day07"); response.addCookie(cookie); } private String buildCookie(String id, HttpServletRequest request) { //当前cookiez值 当前浏览id 回送cookie值 //bookHistory=null 1 1 //bookHistory=2,5,1 1 1,2,5 //bookHistory=2,5,4 1 1,2,5 //bookHistory=2,5 1 1,2,5 String bookHistory = null; Cookie cookies[] = request.getCookies(); for(int i = 0;cookies!=null&&i<cookies.length;i++){ if(cookies[i].getName().equals("bookHistory")){ bookHistory=cookies[i].getValue(); } } // if(bookHistory==null){ // //bookHistory=null 1 1 // return id; // } // // LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory.split("\\,"))); // if(list.contains(id)){ // //bookHistory=2,5,1 1 1,2,5 // list.remove(id); // list.addFirst(id); // } // else{ // //bookHistory=2,5,4 1 1,2,5 // if(list.size()>=3){ // list.removeLast(); // list.addFirst(id); // } // else{ // //bookHistory=2,5 1 1,2,5 // list.addFirst(id); // } // } if(bookHistory==null){ return id; } //先把bookHistory字符串按","拆分为数组,再用Arrays.asList把数组转为List集合,再把List集合转为LinkedList,因为LinkedList对于节点的增删改查很方便 LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory.split("\\,"))); if(list.contains(id)){ list.remove(id); } else{ if(list.size()>=3){ list.removeLast(); } } list.addFirst(id); StringBuffer sb = new StringBuffer(); for(String bid : list){ sb.append(bid+","); } return sb.deleteCharAt(sb.length()-1).toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }