package de.bvb.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 显示商品列表和已经浏览过的商品
 *
 * @author joker
 *
 */
public class CookieDemo11 extends HttpServlet {

    public 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/>");
        for (Entry<String, Book> b : Db.getBooks().entrySet()) {
            out.write("<a target='_blank' href='/web/CookieDemo12?id="
                    + b.getKey() + "'>" + b.getValue().getName() + "</a><br/>");
        }

        // 显示浏览过的商品
        out.write(" <br/> <br/>浏览过的商品: <br/>");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("history")) {
                String[] ids = cookies[i].getValue().split("\\,");
                for (String s : ids) {
                    out.write(Db.getBooks().get(s).getName() + "<br/>");
                }
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }
}

class Db {
    private static LinkedHashMap<String, Book> books = new LinkedHashMap<String, Book>();
    static {
        books.put("1", new Book("1", "javaWeb", "javaweb"));
        books.put("2", new Book("2", "android", "android"));
        books.put("3", new Book("3", "spring", "spring"));
        books.put("4", new Book("4", "strus", "strus"));
        books.put("5", new Book("5", "ios", "ios"));
    }

    public static Map<String, Book> getBooks() {
        return books;
    }
}

class Book {
    private String id;
    private String name;
    private String description;

    public Book(String id, String name, String description) {
        super();
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public Book() {
        super();
    }

    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;
    }

}
package de.bvb.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map.Entry;

import javax.enterprise.inject.ResolutionException;
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.swing.text.DateFormatter;

/**
 * 显示商品详情
 *
 * @author joker
 *
 */
public class CookieDemo12 extends HttpServlet {

    public 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/>");
        String id = request.getParameter("id");
        for (Entry<String, Book> b : Db.getBooks().entrySet()) {
            if (id.equals(b.getKey())) {
                out.write(b.getValue().getId() + "<br/>");
                out.write(b.getValue().getName() + "<br/>");
                out.write(b.getValue().getDescription() + "<br/>");
            }
        }

        // 回写cookie,保存最后浏览的商品id
        String history = buildIds(id, request);
        Cookie cookie = new Cookie("history", history);
        cookie.setMaxAge(1 * 30 * 24 * 60 * 60);
        cookie.setPath("/web");
        response.addCookie(cookie);
    }

    private String buildIds(String id, HttpServletRequest request) {
        String history = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("history")) {
                history = cookies[i].getValue();
            }
        }
        if (history == null) {
            return id;
        }
        LinkedList<String> ids = new LinkedList<String>(Arrays.asList(history
                .split("\\,")));
        if (ids.contains(id)) {
            ids.remove(id);
        } else {
            if (ids.size() >= 3) { // 最多显示3条浏览历史
                ids.removeLast();
            }
        }
        ids.addFirst(id);
        StringBuffer sb = new StringBuffer();
        for (String s : ids) {
            sb.append(s).append(",");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

javaWeb 使用cookie显示商品浏览记录的更多相关文章

  1. Cookie实现商品浏览记录--方式二:JS实现

    使用Cookie实现商品浏览记录:方式二:JS方法实现cookie的获取以及写入.当某一个产品被点击时,触发JS方法.利用JS方法判断一下,此产品是否在浏览记录中.如果不存在,则将产品ID加入到coo ...

  2. 使用Cookie保存商品浏览记录

    数据流程:页面上是商品列表,点击<a href="productServlet">商品名</a> ==>跳转到自定义的servlet中进行处理,先得到 ...

  3. Cookie实现商品浏览记录--方式一:Java实现

    方式一:Java代码方式实现:此种方式实现思路较为顺畅.难点在于,如何实现将最近浏览的产品显示在最前面:实现方式是借助LinkedList提供的remove()方法,先将此id从列表中移除,然后再借助 ...

  4. Java遇见HTML——JSP篇之商品浏览记录的实现

    一.项目总体介绍 使用Cookie实现商品浏览记录. 要实现这个程序采取的是Model1(Jsp+JavaBean)架构实现,具体步骤: 首先要有个数据库,商品表,操作数据库的一个类DBHelper类 ...

  5. (JS实现顾客商品浏览记录以及购物车)Cookie的保存与删除

    //JS实现顾客浏览商品的记录以及实现购物车的功能function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.s ...

  6. 使用cookie实现打印浏览记录的功能

    可以用cookie知识来实现打印浏览记录.这里面用到的思路是将浏览记录以字符串的方式保存到cookie中,当浏览记录增加时,再将其转化为数组. $uri=$_SERVER['REQUEST_URI'] ...

  7. Cookie案例-显示商品浏览历史纪录

    package cn.itcast.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.D ...

  8. javaWeb 使用cookie显示上次访问网站时间

    package de.bvb.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.Date ...

  9. Cookie中图片的浏览记录与cookie读取servle时路径的设置(文字描述)

    public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpSer ...

随机推荐

  1. C++内存对齐总结

    大家都知道,C++空类的内存大小为1字节,为了保证其对象拥有彼此独立的内存地址.非空类的大小与类中非静态成员变量和虚函数表的多少有关. 而值得注意的是,类中非静态成员变量的大小与编译器内存对齐的设置有 ...

  2. C语言 链表排序

    #include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct node{ in ...

  3. 贪吃蛇,JavaScript,效果,鼠标事件

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>鼠 ...

  4. bash shell,调用ffmpeg定期截图

    #!/bin/bash #获取当前目录中所有m3u8文件,并 var=$(ls |grep '.m3u8'|cut -d '.' -f1) #死循环 = ] do #循环每个文件 for stream ...

  5. lua module环境探秘

    module 作用 module (name [, ···]) Creates a module. If there is a table in package.loaded[name], this ...

  6. MySql和SQL Server数据类型 对比

    My Sql 数据类型 SQL Server 数据类型 Yes/No bit Smallint(字节型) tinyint Integer(长整型) int Real(单精度浮点型)    real F ...

  7. Visual Studio 2010配置OpenGL-1.8

    参考博客 : 安装参考 1. http://blog.csdn.net/mooncircle/article/details/5545448 2. http://www.cnblogs.com/moo ...

  8. 洛谷 P1025 数的划分 Label:dp

    题目描述 将整数n分成k份,且每份不能为空,任意两个方案不相同(不考虑顺序). 例如:n=7,k=3,下面三种分法被认为是相同的. 1,1,5; 1,5,1; 5,1,1; 问有多少种不同的分法. 输 ...

  9. Python内置方法的时间复杂度(转)

    原文:http://www.orangecube.net/python-time-complexity 本文翻译自Python Wiki本文基于GPL v2协议,转载请保留此协议. 本页面涵盖了Pyt ...

  10. linux eval命令

    eval 功能说明:重新运算求出参数的内容.语 法:eval [参数]补充说明:eval可读取一连串的参数,然后再依参数本身的特性来执行.参 数:参数不限数目,彼此之间用分号分开. 1.eval命令将 ...