利用Cookie显示商品浏览历史记录

来源:互联网 发布:linux du命令 编辑:程序博客网 时间:2024/05/27 02:33

//代表首页的servlet
public class CookieDemo3 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>");
  Map<String, Book> map=Db.getAll();
  for(Map.Entry<String,Book> me:map.entrySet()){
   Book book = me.getValue();
   out.write("<a href='/day07/servlet/CookieDemo4?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br>");
  }
  //显示以前所看过的商品
  out.write("<br>你曾经看过的商品:<br>");
  Cookie[] cookies=request.getCookies();
  for(int i=0;cookies!=null&&i<cookies.length;i++){
   if(cookies[i].getName().equals("bookHistory")){
    System.out.println("reque:"+cookies[i].getValue());
    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);
 }

}
//模拟数据库的集合
class Db{
 private static Map<String,Book> map =new LinkedHashMap<String,Book>();
 static{
  map.put("1", new Book("1","那些年","tracy","很好的书"));
  map.put("2", new Book("2","活在当下","yaoming","很好的书"));
  map.put("3", new Book("3","javaoa","韦德","很好的书"));
  map.put("4", new Book("4","javajdbc","詹姆斯","很好的书"));
  
 }
 public static Map getAll()
 {
  return map;
 }
 
}
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;
 }
 
}