大型网站一般都用cookie,因为session的会在客户端生成,是服务器压力增大,下面我来介绍一下,cookie的原理和使用
原理如图
使用方法:如如下代码demo1生成cookie,demo2获得cookie
demo1:
import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("lastTime", new Date().toLocaleString()); cookie.setMaxAge(60 * 60); cookie.setValue(new Date().toLocaleString()); cookie.setPath(request.getContextPath());// 设置的是有效路劲,如果没有设置,那就表示当前路径 System.out.println(request.getContextPath()); response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
demo2:
package com.itcast.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookie = request.getCookies(); for (int i = 0; cookie != null && i < cookie.length; i++) { if ("lastTime".equals(cookie[i].getName())) { response.getWriter().write(cookie[i].getValue()); System.out.println(cookie[i].getValue()); } else if (cookie == null) { response.getWriter().write("您是首次访问本站"); Cookie[] cookies = request.getCookies(); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
cookie普遍应用于购物车,是一个减缓服务器压力的好技术,下面我来用4个类为大家模拟一下买书购物功能:
1.书类javabean
package cn.itcast.cookie.javabean; public class Book { private String id; private String name; private String author; private String price; public String getId() { return id; } public void setId(String id) { this.id = id; } public Book() { super(); // TODO Auto-generated constructor stub } 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 getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Book(String id, String name, String author, String price) { super(); this.id = id; this.name = name; this.author = author; this.price = price; } }
2.书店的模拟类,一般用数据库,但是这里我们模拟一些数据:package cn.itcast.cookie.javabean;
import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; public class DB { private static Map<String, Book> books = new LinkedHashMap<String, Book>(); public static Collection<Book> getAll() { return books.values(); } static { books.put("1", new Book("1", "php实战", "老路", "hello")); books.put("2", new Book("2", "android开发", "老徐", "110")); books.put("3", new Book("3", "jdbc开发", "老黎", "106")); books.put("4", new Book("4", "c++算法", "老方", "107")); } public static Book Findbook(String bookid) { return books.get(bookid); } }
3.这个类,有两个功能,第一个,显示全部的书,第二个,在你买书后,刷新能显示你曾经浏览过的书
package com.itcast.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cookie.javabean.Book; import cn.itcast.cookie.javabean.DB; public class ListBookServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); request.getParameter("id"); // 获得商品 Collection<Book> books = DB.getAll(); // 显示商品 for (Book book : books) { out.write("<a href='/day07_cookie/servlet/ShowBookInfo?id=" + book.getId() + "'>" + book.getName() + "</a><br>"); } String bookHistory = null; Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { if ("BookHistory".equals(cookies[i].getName())) { bookHistory = cookies[i].getValue(); break; } } out.write("您浏览过的商品:</br>"); String[] strs = bookHistory.split("\\-");// 将获得的字符串拆分,获取里面的id,用来找到每一本书 for (int j = 0; j < strs.length; j++) { System.out.println("strs[i]=" + strs[j]); Book book = DB.Findbook(strs[j]); out.write(book.getName() + "</br>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
4.显示你购买商品的详细信息,并将你所有的购买的商品的id,拼接成一个1-2-3格式的字符串
package com.itcast.servlet; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cookie.javabean.Book; import cn.itcast.cookie.javabean.DB; public class ShowBookInfo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String id = request.getParameter("id"); Book book = DB.Findbook(id); String BookHistory = makeBookHistory(request, book.getId()); response.getWriter().write( "" + book.getName() + "</br>" + book.getAuthor() + "</br>" + book.getPrice() + "</br>"); Cookie cookie = new Cookie("BookHistory", BookHistory); response.addCookie(cookie); } private String makeBookHistory(HttpServletRequest request, String id) { Cookie[] cookies = request.getCookies(); String BookHistory = null; for (int i = 0; cookies != null && i < cookies.length; i++) { if ("BookHistory".equals(cookies[i].getName())) { BookHistory = cookies[i].getValue(); break; } } if (BookHistory == null) { return id; } String[] strs = BookHistory.split("-");//如果前面获得的id不是null,将返回来的字符串拆分,获得所有的id,存到String[]中 List<String> list = Arrays.asList(strs); LinkedList<String> ids = new LinkedList<String>();//添加到LinkedList,是为了能按照先后顺序显示 ids.addAll(list); if (ids.contains(id)) {// 如果有,移除,并加到第一个 ids.remove(id);// ids.addFirst(id); } if (ids.size() == 3) {//最多显示3个浏览过的商品,如果超过,就删除最后一个 ids.remove(ids.size() - 1); } else { ids.addFirst(id); } StringBuffer sb = new StringBuffer(); for (String str : ids) {//将所有的id,合并成一个1-2-3的字符串,因为一次只能储存一个数据,在cookie中,所以用这个来储存多个id sb.append(str + "-"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }