Cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去。这样,web资源处理的就是用户各自的数据了。
javax.servlet.http.Cookie类用于创建一个Cookie,response接口也中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。 同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。Cookie类的方法:
public Cookie(String name,String value)
setValue与getValue方法
setMaxAge与getMaxAge方法
setPath与getPath方法 /day06
setDomain与getDomain方法
getName方法
一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。
一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。
浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。
注意,删除cookie时,path必须一致,否则不会删除
利用coockie技术实现显示上次登录时间:
//利用cookie技术实现客户端显示上次访问时间 private void test1(HttpServletRequest request, HttpServletResponse response) throws IOException { //1: 获得客户端带来的cookie , 用来读取上次访问的时间, 输出到客户端显示 OutputStream out = response.getOutputStream(); Cookie[] cookies = request.getCookies(); out.write("你上次访问的时间:".getBytes()); for (int i = 0; cookies != null && i < cookies.length; ++i) { if (cookies[i].getName().equals("lastAcessTime")) { String time = cookies[i].getValue(); Date date = new Date(Long.parseLong(time)); out.write(date.toLocaleString().getBytes()); } } //2: 创建新的Cookie ,覆盖原来的Cookie , 存储最近一次访问时间 Cookie cookie = new Cookie("lastAcessTime", System.currentTimeMillis()+""); cookie.setMaxAge(1*30*24*60*60); //设置cookie缓存一个月, 以秒为单位, 默认为浏览器进程 cookie.setPath("/Test"); //设置cookie的有效目录 如果不设置默认为访问资源坐在的目录 response.addCookie(cookie); }
利用coockie实现 显示用户上次浏览过的商品
显示所有书籍,和用户浏览过的数据的servlet
package cn.cookie; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; 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 javax.servlet.http.HttpSession; public class CookieDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1:显示所有书籍 HttpSession session = request.getSession(); Map<String, Book> books = DB.getALL(); session.setAttribute("books", books); //2:显示曾经浏览过的书籍 Cookie[] cookies = request.getCookies(); String[] ids = null; for (int i = 0; cookies != null && i < cookies.length; ++i) { if (cookies[i].getName().equals("bookHistory")) { ids = cookies[i].getValue().split("\\,"); cookies[i].setMaxAge(0); } } System.out.println("ids = " + ids); List<Book> lookedBooks = new ArrayList<Book>(); for (int i = 0; ids != null && i < ids.length; ++i) { Book b = DB.getALL().get(ids[i]); lookedBooks.add(b); } session.setAttribute("lookedBooks", lookedBooks); request.getRequestDispatcher("indexcookie.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } class DB{ private static Map<String, Book> map = new LinkedHashMap<String, Book>(); static { map.put("1", new Book("1", "javaweb", "Tom")); map.put("2", new Book("2", "C++", "Jery")); map.put("3", new Book("3", "C", "Bob")); map.put("4", new Book("4", "C#", "HH")); map.put("5", new Book("5", "JDBC", "TT")); map.put("6", new Book("6", "Orcal", "GG")); } public static Map<String, Book> getALL() { return map; } }
购买Servlet 这里要处理cookie
package cn.cookie; import java.io.IOException; import java.io.PrintWriter; 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 javax.servlet.http.HttpSession; public class CookieDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1: 得到要查看的书籍 String id = request.getParameter("id"); Book book = DB.getALL().get(id); HttpSession session = request.getSession(); session.setAttribute("book", book); //:重写cookie String value = buildCookie(id, request); System.out.println("value = " + value); Cookie cookie = new Cookie("bookHistory", value); cookie.setMaxAge(30*24*60*60); cookie.setPath("/Test"); response.addCookie(cookie); request.getRequestDispatcher("bookDetail.jsp").forward(request, response); } private String buildCookie(String id, HttpServletRequest request) { 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(); break; } } if (bookHistory == null) return id; LinkedList<String> ids = new LinkedList<String>(Arrays.asList(bookHistory.split("\\,"))); if (ids.contains(id)) { ids.remove(id); } else { if (ids.size() >= 3) { ids.removeLast(); } } ids.addFirst(id); StringBuilder sb = new StringBuilder(); for (String i : ids) { sb.append(i + ","); } sb.deleteCharAt(sb.length() - 1); System.out.println("sb = " + sb.toString()); return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
显示页面:
<body> <font color="red" size="5">所有书籍 : </font> <br/> <c:forEach var="books" items="${books}"> <a href="/Test/CookieDemo2?id=${ books.key }"> ${books.key} : <c:set var="book" value="${ books.value }"></c:set> ${ book.name } ${ book.author } <br/> </a> </c:forEach> <font color="red" size="5">您看过的书籍 : </font> <br/> <c:forEach var="lookedBook" items="${ lookedBooks }"> ${ lookedBook["name"] } </c:forEach> </body>