首页 > 代码库 > Cookie

Cookie

Cookie

利用cookie实现: 记录上次访问时间

response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.print("<a href=http://www.mamicode.com/‘ServletDemo/cookieDemo2‘>删除上次访问时间");        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 =http://www.mamicode.com/ 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);        response.addCookie(cookie);                response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        response.getWriter().write("删除cookie成功<br /><a href=http://www.mamicode.com/‘ServletDemo/cookieDemo1‘>返回");

 

模拟浏览商品的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=http://www.mamicode.com/‘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=http://www.mamicode.com/‘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() {        super();    }    private String id;    public Book(String id, String name, String description) {        super();        this.id = id;        this.name = name;        this.description = description;    }    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=http://www.mamicode.com/‘ServletDemo/cookieDemo3‘>返回");        // 构造Cookie 返回给浏览器        String cookValue =http://www.mamicode.com/ 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 bookHistory=2,3,1 1         * bookHistory=2,4,5 1 bookHistory= 2,3 1         */        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) {                    return id;                }                LinkedList list = new LinkedList(Arrays.asList(bookHistory                        .split("\\,")));                if (list.contains(id)) {                    list.remove(id);                } else {                    if (list.size() >= 5) {                        list.removeLast();                    }                }                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);    }}

 

Cookie