Java遇見HTML——JSP篇之商品瀏覽記錄的實現


一、項目總體介紹

使用Cookie實現商品瀏覽記錄。

要實現這個程序采取的是Model1(Jsp+JavaBean)架構實現,具體步驟:

  • 首先要有個數據庫,商品表,操作數據庫的一個類DBHelper類
  • 創建實體類(與數據庫表一一對應)
  • 創建業務邏輯類(DAO)
  • 創建頁面層

二、DBHelper類設計

 1 package util;  2  3 import java.sql.Connection;  4 import java.sql.DriverManager;  5  6 public class DBHelper {  7  8 private static final String driver = "com.mysql.jdbc.Driver"; //數據庫驅動  9 //連接數據庫的URL地址 10 private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8"; 11 private static final String username="root";//數據庫的用戶名 12 private static final String password="root";//數據庫的密碼 13 14 private static Connection conn=null; 15 16 //靜態代碼塊負責加載驅動 17 static 18  { 19 try 20  { 21  Class.forName(driver); 22  } 23 catch(Exception ex) 24  { 25  ex.printStackTrace(); 26  } 27  } 28 29 //單例模式返回數據庫連接對象 30 public static Connection getConnection() throws Exception 31  { 32 if(conn==null)//連接為空 33  { 34 conn = DriverManager.getConnection(url, username, password); 35 return conn; 36  } 37 return conn;//連接不為空,說明這個conn曾經被實例化過。被實例化也是通過DriverManager實例化了。 38 //由於這是單例模式,意味着這個連接對象在整個服務中只有一份拷貝 39  } 40 41 //測試DBHelper類 42 public static void main(String[] args) { 43 try 44  { 45 Connection conn = DBHelper.getConnection(); 46 if(conn!=null) 47  { 48 System.out.println("數據庫連接正常!"); 49  } 50 else 51  { 52 System.out.println("數據庫連接異常!"); 53  } 54  } 55 catch(Exception ex) 56  { 57  ex.printStackTrace(); 58  } 59 60  } 61 }

三、商品實體類設計

數據庫shopping中items表:

對應的實體類:

 1 package entity;  2  3 //商品類  4 public class Items {  5  6 private int id; // 商品編號  7 private String name; // 商品名稱  8 private String city; // 產地  9 private int price; // 價格 10 private int number; // 庫存 11 private String picture; // 商品圖片 12 13 public int getId() { 14 return id; 15  } 16 17 public void setId(int id) { 18 this.id = id; 19  } 20 21 public String getName() { 22 return name; 23  } 24 25 public void setName(String name) { 26 this.name = name; 27  } 28 29 public String getCity() { 30 return city; 31  } 32 33 public void setCity(String city) { 34 this.city = city; 35  } 36 37 public int getPrice() { 38 return price; 39  } 40 41 public void setPrice(int price) { 42 this.price = price; 43  } 44 45 public int getNumber() { 46 return number; 47  } 48 49 public void setNumber(int number) { 50 this.number = number; 51  } 52 53 public String getPicture() { 54 return picture; 55  } 56 57 public void setPicture(String picture) { 58 this.picture = picture; 59  } 60 61 }

四、獲取所有商品資料方法的實現

 1 package dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.util.ArrayList;
 7 
 8 import util.DBHelper;
 9 
10 import entity.Items;
11 
12 //商品的業務邏輯類
13 public class ItemsDAO {
14 
15     // 獲得所有的商品信息
16     public ArrayList<Items> getAllItems() {
17         Connection conn = null;
18         PreparedStatement stmt = null;
19         ResultSet rs = null;
20         ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
21         try {
22             conn = DBHelper.getConnection();
23             String sql = "select * from items;"; // SQL語句
24             stmt = conn.prepareStatement(sql);
25             rs = stmt.executeQuery();
26             while (rs.next()) {
27                 Items item = new Items();
28                 item.setId(rs.getInt("id"));
29                 item.setName(rs.getString("name"));
30                 item.setCity(rs.getString("city"));
31                 item.setNumber(rs.getInt("number"));
32                 item.setPrice(rs.getInt("price"));
33                 item.setPicture(rs.getString("picture"));
34                 list.add(item);// 每次遍歷時把一個商品加入集合
35             }
36             return list; // 返回集合。
37         } catch (Exception ex) {
38             ex.printStackTrace();
39             return null;
40         } finally {
41             //finally釋放資源(從小到大釋放資源rs,stmt。注意連接對象conn不要釋放,因為它是單例模式,一旦釋放了,后面的方法就沒法使用了)
42             // 釋放數據集對象
43             if (rs != null) {
44                 try {
45                     rs.close();//這個地方會拋出異常
46                     rs = null;
47                 } catch (Exception ex) {
48                     ex.printStackTrace();
49                 }
50             }
51             // 釋放語句對象
52             if (stmt != null) {
53                 try {
54                     stmt.close();
55                     stmt = null;
56                 } catch (Exception ex) {
57                     ex.printStackTrace();
58                 }
59             }
60         }
61 
62     }
63 
64 }

五、所有商品信息顯示

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%@ page import="entity.Items"%>
 3 <%@ page import="dao.ItemsDAO"%>
 4 <%
 5 String path = request.getContextPath();
 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 7 %>
 8 
 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11   <head>
12     <base href="<%=basePath%>">
13     
14     <title>My JSP 'index.jsp' starting page</title>
15     <meta http-equiv="pragma" content="no-cache">
16     <meta http-equiv="cache-control" content="no-cache">
17     <meta http-equiv="expires" content="0">    
18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19     <meta http-equiv="description" content="This is my page">
20     <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23     <style type="text/css">
24        div{
25           float:left;
26           margin: 10px;
27        }
28        div dd{
29           margin:0px;
30           font-size:10pt;
31        }
32        div dd.dd_name
33        {
34           color:blue;
35        }
36        div dd.dd_city
37        {
38           color:#000;
39        }
40     </style>
41   </head>
42   
43   <body>
44     <h1>商品展示</h1>
45     <hr>
46     <center>
47     <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
48       <tr>
49         <td>
50           <!-- 商品循環開始 -->
51            <% 
52                ItemsDAO itemsDao = new ItemsDAO(); 
53                ArrayList<Items> list = itemsDao.getAllItems();
54                if(list!=null&&list.size()>0)
55                {
56                    for(int i=0;i<list.size();i++)
57                    {
58                       Items item = list.get(i);
59            %>   
60           <div>
61              <dl>
62                <dt>
63                  <a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
64                </dt>
65                <dd class="dd_name"><%=item.getName() %></dd> 
66                <dd class="dd_city">產地:<%=item.getCity() %>&nbsp;&nbsp;價格:¥ <%=item.getPrice() %></dd> 
67              </dl>
68           </div>
69           <!-- 商品循環結束 -->
70           <%
71                    }
72               } 
73           %>
74         </td>
75       </tr>
76     </table>
77     </center>
78   </body>
79 </html>

六、商品詳細信息顯示

 在ItemsDAO.java中添加如下代碼:

 1 // 根據商品編號獲得商品資料
 2     public Items getItemsById(int id) {
 3         Connection conn = null;
 4         PreparedStatement stmt = null;
 5         ResultSet rs = null;
 6         try {
 7             conn = DBHelper.getConnection();
 8             String sql = "select * from items where id=?;"; // SQL語句
 9             stmt = conn.prepareStatement(sql);
10             stmt.setInt(1, id);
11             rs = stmt.executeQuery();
12             if (rs.next()) {
13                 Items item = new Items();
14                 item.setId(rs.getInt("id"));
15                 item.setName(rs.getString("name"));
16                 item.setCity(rs.getString("city"));
17                 item.setNumber(rs.getInt("number"));
18                 item.setPrice(rs.getInt("price"));
19                 item.setPicture(rs.getString("picture"));
20                 return item;
21             } else {
22                 return null;
23             }
24         } catch (Exception ex) {
25             ex.printStackTrace();
26             return null;
27         } finally {
28             // 釋放數據集對象
29             if (rs != null) {
30                 try {
31                     rs.close();
32                     rs = null;
33                 } catch (Exception ex) {
34                     ex.printStackTrace();
35                 }
36             }
37             // 釋放語句對象
38             if (stmt != null) {
39                 try {
40                     stmt.close();
41                     stmt = null;
42                 } catch (Exception ex) {
43                     ex.printStackTrace();
44                 }
45             }
46 
47         }
48     }

在details.jsp添加如下代碼:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'details.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
       div{
          float:left;
          margin-left: 30px;
          margin-right:30px;
          margin-top: 5px;
          margin-bottom: 5px;
       }
       div dd{
          margin:0px;
          font-size:10pt;
       }
       div dd.dd_name
       {
          color:blue;
       }
       div dd.dd_city
       {
          color:#000;
       }
    </style>
  </head>
  
  <body>
    <h1>商品詳情</h1>
    <hr>
    <center>
      <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <!-- 商品詳情 -->
          <% 
             ItemsDAO itemDao = new ItemsDAO();
             Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
             if(item!=null)
             {
          %>
          <td width="70%" valign="top">
             <table>
               <tr>
                 <td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
               </tr>
               <tr>
                 <td><B><%=item.getName() %></B></td> 
               </tr>
               <tr>
                 <td>產地:<%=item.getCity()%></td>
               </tr>
               <tr>
                 <td>價格:<%=item.getPrice() %></td>
               </tr> 
             </table>
          </td>
          <% 
            }
          %>
        </tr>
      </table>
    </center>
  </body>
</html>

七、使用Cookie實現保存商品瀏覽記錄

如何把瀏覽記錄保存在cookie中?

因為商品編號是唯一的,我們可以獲取商品的編號,自然而然可以獲取商品的信息。那么用戶在每一次點擊商品的詳情的時候,他會把商品的編號傳給details.jsp頁面,那么我們可以想辦法在details.jsp頁面當中把傳過來的商品編號給它保存在一個字符串當中。

主要思路:

把每次瀏覽的商品編號保存在字符串中,編號和編號之間用分隔符分隔,每次取出前五條記錄。

(把字符串保存在cookie當中,每次只要在cookie中讀取這個字符串就可以了。把這個字符串通過分隔符轉換成字符串數組,數組中的每個元素實際上就是商品編號)

大致思路:
1、用一個字符串來記錄瀏覽商品的id記錄。***字符串處理:將id添加到字符串中,並用','隔開。操作方式:str += id + ",";這樣所有的記錄都保存在字符串中,如:1,3,5,1,....
2、通過request.getCookies()遍歷cookie集合,通過cookie.getName().equals(strname)查詢用於保存字符串的cookie,通過cookie.getValue()得到字符串后傳入邏輯業務中的方法。
3、在邏輯業務操作中,定義一個方法接受字符串,取得字符串后,使用str.sqlit(",")將字符串分割為字符串數組[1,3,5,1...],這樣就獲得了商品id的瀏覽記錄。
4、之后就是通過遍歷和添加數組,最后返回瀏覽記錄的數組即可

 1 //獲取最近瀏覽的前五條商品信息
 2     public ArrayList<Items> getViewList(String list)
 3     {
 4         System.out.println("list:"+list);
 5         ArrayList<Items> itemlist = new ArrayList<Items>();
 6         int iCount=5; //每次返回前五條記錄
 7         if(list!=null&&list.length()>0)
 8         {
 9             String[] arr = list.split(",");
10             System.out.println("arr.length="+arr.length);
11             //如果商品記錄大於等於5條
12             if(arr.length>=5)
13             {
14                for(int i=arr.length-1;i>=arr.length-iCount;i--)
15                {
16                   itemlist.add(getItemsById(Integer.parseInt(arr[i])));  
17                }
18             }
19             else
20             {
21                 for(int i=arr.length-1;i>=0;i--)
22                 {
23                     itemlist.add(getItemsById(Integer.parseInt(arr[i])));
24                 }
25             }
26             return itemlist;
27         }
28         else
29         {
30             return null;
31         }
32         
33     }

detail.jsp

  1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
  2 <%@ page import="entity.Items"%>
  3 <%@ page import="dao.ItemsDAO"%>
  4 <%
  5 String path = request.getContextPath();
  6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7 %>
  8 
  9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 10 <html>
 11   <head>
 12     <base href="<%=basePath%>">
 13     
 14     <title>My JSP 'details.jsp' starting page</title>
 15     
 16     <meta http-equiv="pragma" content="no-cache">
 17     <meta http-equiv="cache-control" content="no-cache">
 18     <meta http-equiv="expires" content="0">    
 19     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 20     <meta http-equiv="description" content="This is my page">
 21     <!--
 22     <link rel="stylesheet" type="text/css" href="styles.css">
 23     -->
 24     <style type="text/css">
 25        div{
 26           float:left;
 27           margin-left: 30px;
 28           margin-right:30px;
 29           margin-top: 5px;
 30           margin-bottom: 5px;
 31        }
 32        div dd{
 33           margin:0px;
 34           font-size:10pt;
 35        }
 36        div dd.dd_name
 37        {
 38           color:blue;
 39        }
 40        div dd.dd_city
 41        {
 42           color:#000;
 43        }
 44     </style>
 45   </head>
 46   
 47   <body>
 48     <h1>商品詳情</h1>
 49     <hr>
 50     <center>
 51       <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
 52         <tr>
 53           <!-- 商品詳情 -->
 54           <% 
 55              ItemsDAO itemDao = new ItemsDAO();
 56              Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
 57              if(item!=null)
 58              {
 59           %>
 60           <td width="70%" valign="top">
 61              <table>
 62                <tr>
 63                  <td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
 64                </tr>
 65                <tr>
 66                  <td><B><%=item.getName() %></B></td> 
 67                </tr>
 68                <tr>
 69                  <td>產地:<%=item.getCity()%></td>
 70                </tr>
 71                <tr>
 72                  <td>價格:<%=item.getPrice() %></td>
 73                </tr> 
 74              </table>
 75           </td>
 76           <% 
 77             }
 78           %>
 79           <% 
 80               String list ="";
 81               //從客戶端獲得Cookies集合
 82               Cookie[] cookies = request.getCookies();
 83               //遍歷這個Cookies集合
 84               if(cookies!=null&&cookies.length>0)
 85               {
 86                   for(Cookie c:cookies)
 87                   {
 88                       if(c.getName().equals("ListViewCookie"))
 89                       {
 90                          list = c.getValue();
 91                       }
 92                   }
 93               }
 94               
 95               list+=request.getParameter("id")+",";
 96               //如果瀏覽記錄超過1000條,清零.
 97               String[] arr = list.split(",");
 98               if(arr!=null&&arr.length>0)
 99               {
100                   if(arr.length>=1000)
101                   {
102                       list="";
103                   }
104               }
105               Cookie cookie = new Cookie("ListViewCookie",list);
106               response.addCookie(cookie);
107           
108           %>
109           <!-- 瀏覽過的商品 -->
110           <td width="30%" bgcolor="#EEE" align="center">
111              <br>
112              <b>您瀏覽過的商品</b><br>
113              <!-- 循環開始 -->
114              <% 
115                 ArrayList<Items> itemlist = itemDao.getViewList(list);
116                 if(itemlist!=null&&itemlist.size()>0 )
117                 {
118                    System.out.println("itemlist.size="+itemlist.size());
119                    for(Items i:itemlist)
120                    {
121                          
122              %>
123              <div>
124              <dl>
125                <dt>
126                  <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
127                </dt>
128                <dd class="dd_name"><%=i.getName() %></dd> 
129                <dd class="dd_city">產地:<%=i.getCity() %>&nbsp;&nbsp;價格:<%=i.getPrice() %></dd> 
130              </dl>
131              </div>
132              <% 
133                    }
134                 }
135              %>
136              <!-- 循環結束 -->
137           </td>
138         </tr>
139       </table>
140     </center>
141   </body>
142 </html>

最終的案例界面:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM