【JSP開發】利用cookie實現商品瀏覽記錄

在主頁中顯示商品,點擊商品可以查看商品的具體信息,帶用戶瀏覽完之後,回到主頁,就會看到自己曾經瀏覽過什麼商品。


商品主頁Servlet
  1. CookieDemo3.java:  
  2. package cn.edu.cookie;  
  3.   
  4.   
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.util.LinkedHashMap;  
  8. import java.util.Map;  
  9.   
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.Cookie;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16. //代表首頁的Servlet  
  17. public class CookieDemo3 extends HttpServlet {  
  18.   
  19.   
  20.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  21.             throws ServletException, IOException {  
  22.           
  23.         response.setCharacterEncoding("UTF-8");  
  24.         response.setContentType("text/html;charset=UTF-8");  
  25.         PrintWriter out=response.getWriter();  
  26.           
  27.        //1.輸出網站所有商品  
  28.         out.write("本網站有如下商品:<br/>");  
  29.         Map<String,Book> map = Db.getAll();  
  30.         for(Map.Entry<String, Book> entry :map.entrySet())  
  31.         {  
  32.             Book book=entry.getValue();  
  33.             out.print("<a href='/day07/CookieDemo4?id="+book.getId()+"' terget='_blank'>"+book.getName()+"</a><br/>");  
  34.         }  
  35.           
  36.        //2.輸出用戶曾經看過的商品  
  37.         out.print("您曾經看過如下商品:<br/>");  
  38.         Cookie cookies[]= request.getCookies();  
  39.         for(int i=0;cookies!=null&&i<cookies.length;i++)  
  40.         {  
  41.             //是不是要加if(cookies[i].getName().equals("BookHistory"))判斷?  
  42.             String ids[]=cookies[i].getValue().split("\\,");  
  43.             for(String id:ids){  
  44.                 Book book=(Book)Db.getAll().get(id);  
  45.                 out.print(book.getName()+"<br/>");  
  46.             }  
  47.               
  48.         }  
  49.     }  
  50.   
  51.   
  52.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  53.             throws ServletException, IOException {  
  54.        doGet(request,response);  
  55.     }  
  56.   
  57.   
  58. }  
  59.   
  60.   
  61. //如果有檢索數據的需求,用雙列(Map)的容器,若沒有用單列的(List)  
  62. //模擬數據庫  
  63. class Db{  
  64.     private static Map<String,Book> map=new LinkedHashMap();//HashMap取出來和存進去的順序不是一致的(自己測試)  
  65.     //類初始化代碼(寫在靜態代碼塊裏)  
  66.     static{  
  67.         map.put("1",new Book("1","JAVAWEB開發","老張","一本好書!"));  
  68.         map.put("2",new Book("2","JDBC開發","老張","一本好書!"));  
  69.         map.put("3",new Book("3","Spring開發","老黎","一本好書!"));  
  70.         map.put("4",new Book("4","struts開發","老畢","一本好書!"));  
  71.         map.put("5",new Book("5","android開發","老黎","一本好書!"));  
  72.     }  
  73.       
  74.     public static Map getAll(){  
  75.         return map;  
  76.     }  
  77. }  
  78.   
  79.   
  80. class Book{  
  81.     private String id;  
  82.     private String name;  
  83.     private String author;  
  84.     private String description;  
  85.       
  86.     public Book(){  
  87.         super();  
  88.     }  
  89.     public Book(String id, String name, String author, String description) {  
  90.         super();  
  91.         this.id = id;  
  92.         this.name = name;  
  93.         this.author = author;  
  94.         this.description = description;  
  95.     }  
  96.     public String getId() {  
  97.         return id;  
  98.     }  
  99.     public void setId(String id) {  
  100.         this.id = id;  
  101.     }  
  102.     public String getName() {  
  103.         return name;  
  104.     }  
  105.     public void setName(String name) {  
  106.         this.name = name;  
  107.     }  
  108.     public String getAuthor() {  
  109.         return author;  
  110.     }  
  111.     public void setAuthor(String author) {  
  112.         this.author = author;  
  113.     }  
  114.     public String getDescription() {  
  115.         return description;  
  116.     }  
  117.     public void setDescription(String description) {  
  118.         this.description = description;  
  119.     }  
  120.       
  121.       
  122. }  

CookieDemo4.java是每件商品的詳細信息Servlet,在這裏,cookie中的"BookHistory"就是存儲的瀏覽記錄,記錄的是
瀏覽每件商品的id記錄順序的字符串。組建該字符串的時候需要注意一下四種情況:
1.當一件商品都沒有瀏覽過時,即BookHistory=null 
此時加入的商品直接組成字符串CookieValue即可,假設此時瀏覽過id=1的商品,
CookieValue="1";

2.當瀏覽的商品是以前瀏覽過的,即BookHistory="2,5,1"的時候此時又瀏覽了id=1的

商品,這個時候,就要找到原來的那個id,刪除它,將此次瀏覽的記錄加入到最前面。

即BookHistory="2,5,1"變成了BookHistory="1,2,5"


3.由於我們的商品瀏覽記錄有限,只記錄前三個,所以每當新的記錄加入的時候,要判斷
是否滿三個,滿了的話,刪除最後一個,將最新的加入到最前面。
如BookHistory=2,5,4,當又瀏覽了1商品,要改成BookHistory=1,2,5

4.如果不滿3個,又不和以前的重複,直接將記錄加在最前面即可
如BookHistory=2,5的時候,又瀏覽了1商品,此時BookHistory=1,2,5

CookieDemo4.java
  1. package cn.edu.cookie;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.util.Arrays;  
  7. import java.util.LinkedList;  
  8.   
  9.   
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.Cookie;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15. //顯示商品詳細信息的Servlet  
  16. public class CookieDemo4 extends HttpServlet {  
  17.   
  18.   
  19.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  20.             throws ServletException, IOException {  
  21.         response.setCharacterEncoding("UTF-8");  
  22.         response.setContentType("text/html;charset=UTF-8");  
  23.         PrintWriter out=response.getWriter();  
  24.           
  25.         //根據用戶帶過來的id,顯示相應商品的詳細信息  
  26.         //getParameter是拿到客戶機帶過來的數據(通過表單和鏈接傳遞的參數使用getParameter)  
  27.         String id =request.getParameter("id");//當兩個Web組件之間爲轉發關係時採用getAttribute  
  28.         Book book=(Book) Db.getAll().get(id);  
  29.   
  30.   
  31.         out.write(book.getId()+"<br/>");  
  32.         out.write(book.getAuthor()+"<br/>");  
  33.         out.write(book.getName()+"<br/>");  
  34.         out.write(book.getDescription()+"<br/>");  
  35.           
  36.         //構建cookie,回寫給瀏覽器  
  37.           
  38.         /*一個web應用最多能被瀏覽器記錄20個左右的cookie 
  39.                            所以這裏要把大量的cookie記錄到一起,記錄成一個cookie*/  
  40.         String CookieValue =buildCookie(id,request);  
  41.         Cookie cookie=new Cookie("BookHistory",CookieValue);  
  42.         cookie.setMaxAge(1*30*24*3600);  
  43.         cookie.setPath("/day07");  
  44.         response.addCookie(cookie);  
  45.     }  
  46.   
  47.   
  48.     private String buildCookie(String id, HttpServletRequest request) {  
  49.           
  50.         //四種cookie情況  
  51.         //BookHistory=null   1   1  
  52.         //BookHistory=2,5,1   1   1,2,5  
  53.         //BookHistory=2,5,4   1   1,2,5  
  54.         //BookHistory=2,5   1   1,2,5  
  55.           
  56.         String BookHistory=null;  
  57.         Cookie cookies[]=request.getCookies();  
  58.         for(int i=0;cookies!=null&&i<cookies.length;i++){  
  59.             if(cookies[i].getName().equals("BookHistory")){  
  60.                 BookHistory=cookies[i].getValue();  
  61.             }  
  62.         }  
  63.           
  64.         if(BookHistory==null){  
  65.             return id;  
  66.         }  
  67.           
  68.         //分割成數組,之後將數組轉成集合,集合轉成鏈表  
  69.         LinkedList<String> list=new LinkedList(Arrays.asList(BookHistory.split("\\,")));  
  70.         //分情況分配新的cookie值  
  71.         if(list.contains(id)){  
  72.             //BookHistory=2,5,1   1   1,2,5  
  73.             list.remove(id);  
  74.             list.addFirst(id);  
  75.         }else{  
  76.             if(list.size()>=3){  
  77.                 //BookHistory=2,5,4   1   1,2,5  
  78.                 list.removeLast();  
  79.                 list.addFirst(id);  
  80.             }else{  
  81.                 //BookHistory=2,5   1   1,2,5  
  82.                 //BookHistory=null   1   1  
  83.                 list.addFirst(id);  
  84.             }  
  85.         }  
  86.           
  87.         StringBuffer sb=new StringBuffer();  
  88.         for(String bid : list){  
  89.             sb.append(bid+",");  
  90.         }  
  91.           
  92.         return sb.deleteCharAt(sb.length()-1).toString();  
  93.     }  
  94.   
  95.   
  96.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  97.             throws ServletException, IOException {  
  98.         doGet(request,response);  
  99.     }  
  100.   
  101.   
  102. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章