zoukankan      html  css  js  c++  java
  • 利用Cookie,实现动态显示用户曾经浏览过的商品

    1、在DisPlay的servlet中主要做两件事情

         1.1显示在出售的商品

         1.2显示顾客曾经浏览的商品

    DisPlay的代码如下:

    package com.baowei.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    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 Display extends HttpServlet {
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            
            doPost(req, resp);
        }
        
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            
            //显示所有的图书
            PrintWriter  out = resp.getWriter();
            out.print("本书店出售的图书如下:<br/>");
            
            Map<String,Book> books = DB.getDBMap();
            Set<Entry<String, Book>> set = books.entrySet();
            Iterator<Entry<String, Book>>  it = set.iterator();
            while(it.hasNext()){
                Entry<String, Book> entry = it.next();
                Book book = entry.getValue();
                out.print("<a href='/HuiHuaTest/BookDetail?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
                    
            }
            
            //用户最近看过的图书
            out.print("你最近浏览过的图书如下:<br/>");
            Cookie cookie = null;
            Cookie [] cookies = req.getCookies();
            for (int   i = 0; cookies != null &&   i < cookies.length;   i++) { 
                if(cookies[i].getName().equals("bookHistory")){
                    cookie = cookies[i];
                }
            }
            
            if(cookie!=null){
                //找到了bookHistory这个cookie
                String bookHistory = cookie.getValue();   //4_6_1
                String ids[] = bookHistory.split("\_"); //这样划分更好
                for(String id: ids){
                    Book book = (Book) DB.getDBMap().get(id);
                    out.print(book.getName() + "<br/>");
                }
            }
            
        }
    
    }

    2. 对于图书的详细介绍的BookDetail的servlet,也是两个功能

       2.1 介绍商品的详细信息

       2.2 将浏览过的商品的信息加入到Cookie中,并且将Cookie写回浏览器

    BookDetail的实现代码如下:

     1 package com.baowei.cookie;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.Arrays;
     6 import java.util.LinkedList;
     7 
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.Cookie;
    10 import javax.servlet.http.HttpServlet;
    11 import javax.servlet.http.HttpServletRequest;
    12 import javax.servlet.http.HttpServletResponse;
    13 
    14 public class BookDetail extends HttpServlet {
    15 
    16     public void doGet(HttpServletRequest request, HttpServletResponse response)
    17             throws ServletException, IOException {
    18 
    19         doPost(request, response);
    20 
    21     }
    22 
    23     public void doPost(HttpServletRequest request, HttpServletResponse response)
    24             throws ServletException, IOException {
    25 
    26         response.setContentType("text/html;charset=UTF-8");
    27         response.setCharacterEncoding("UTF-8");
    28         PrintWriter out = response.getWriter();
    29 
    30         // 1.根据用户带过来的id值,显示相应商品的信息
    31         out.print("您想看的书的详细信息为:<br/>");
    32         String id = request.getParameter("id");
    33         Book book = (Book) DB.getDBMap().get(id);
    34         out.print(book.getId() + "<br/>");
    35         out.print(book.getName() + "<br/>");
    36         out.print(book.getAuthor() + "<br/>");
    37 
    38         // 2.以cookie的形式回写该商品的id号给浏览器
    39         String bookHistory = makeCookie(book.getId(), request);
    40         Cookie cookie = new Cookie("bookHistory", bookHistory);
    41         //cookie.setMaxAge(10000); //将Cookie保存在硬盘内
    42         response.addCookie(cookie);
    43 
    44     }
    45 
    46     // 根据用户原来看过的书,以及现在看的书的id,构建新的cookie值
    47     private String makeCookie(String id, HttpServletRequest request) {
    48 
    49         // bookHistory=null    3   bookHistory=3
    50         // bookHistory=2_1_5   3   bookHistory=3_2_1
    51         // bookHistory=2 3     3   bookHistory=3_2
    52         // bookHistory=2_3     3   bookHistory=3_2
    53 
    54         // 1.得到用户曾经看过的书
    55         String bookHistory = null;
    56         Cookie cookies[] = request.getCookies();
    57         for (int i = 0; cookies != null && i < cookies.length; i++) {
    58             if (cookies[i].getName().equals("bookHistory")) {
    59                 bookHistory = cookies[i].getValue();
    60             }
    61         }
    62 
    63         if (bookHistory == null) {
    64             bookHistory = id;
    65             return bookHistory;
    66         }
    67 
    68         // bookHistory=1_2_5 代表用户曾经看一些书,接着程序要得到用户曾经看过什么书
    69         String ids[] = bookHistory.split("_");
    70         // 为了检测数组中是否包含当前id,我们应该把数据转成集合,并且还要转成链表结构的集合
    71         LinkedList<String> idList = new LinkedList(Arrays.asList(ids));
    72     
    73         if (idList.contains(id)) {
    74             idList.remove(id);
    75         } else {
    76             if (idList.size() >= 5) {
    77                 idList.removeLast();
    78             }
    79         }
    80         idList.addFirst(id);
    81 
    82         StringBuffer sb = new StringBuffer();
    83         for (String lid : idList) { // 1_2_3_
    84             sb.append(lid + "_");
    85         }
    86 
    87         return sb.deleteCharAt(sb.length() - 1).toString();
    88     }
    89 
    90 }

    上面两个程序中用到的Book类和DB类如下:

    Book类的代码:

     1 package com.baowei.cookie;
     2 
     3 public class Book {
     4     
     5     private String id;
     6     private String name;
     7     private String author;
     8     
     9     public Book() {
    10 
    11     }
    12     
    13     public Book(String id, String name, String author) {
    14         this.id = id;
    15         this.name = name;
    16         this.author = author;
    17     }
    18     public String getId() {
    19         return id;
    20     }
    21     public void setId(String id) {
    22         this.id = id;
    23     }
    24     public String getName() {
    25         return name;
    26     }
    27     public void setName(String name) {
    28         this.name = name;
    29     }
    30     public String getAuthor() {
    31         return author;
    32     }
    33     public void setAuthor(String author) {
    34         this.author = author;
    35     }
    36     
    37     
    38 
    39 }

    DB类的代码如下:

    package com.baowei.cookie;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class DB {
        
        static Map<String,Book>   map = new HashMap<String,Book>();
        
        static {
            
            map.put("1", new Book("1","JavaWeb开发","张保卫") );
            map.put("2", new Book("2","操作系统","张保卫") );
            map.put("3", new Book("3","Spring开发","张保卫") );
            map.put("4", new Book("4","Struts2开发","张保卫") );
            map.put("5", new Book("5","Java基础开发","张保卫") );
            map.put("6", new Book("6","数据结构","张保卫") );
            map.put("7", new Book("7","ACM","张保卫") );
            map.put("8", new Book("8","计算机网络","张保卫") );
            map.put("9", new Book("9","软件工程","张保卫") );
            map.put("10", new Book("10","Android开发","张保卫") );    
        }
        
        public static Map<String,Book> getDBMap(){ 
            return map;   
        }
       
    }
  • 相关阅读:
    一般图最大匹配
    UOJ164 线段树历史最值查询
    一个经典的排列组合面试题目
    动态代理理解
    JAVA nio
    hadoop NameNode 实现分析
    以一个上传文件的例子来说 DistributedFileSystem
    hadoop IPC 源代码分析
    hadoop DataNode实现分析
    HDFS 整体把握
  • 原文地址:https://www.cnblogs.com/zhangbaowei/p/4676577.html
Copyright © 2011-2022 走看看