JSP 商品瀏覽[Web application]

JSP 商品信息[Web]

採用Model1(jsp+Javabean)實現css

  • 實現DBHelper類(鏈接數據庫)
  • 建立實體類
  • 建立業務邏輯類(DAO)
  • 建立頁面層

1、環境準備

1.1 MySQL 安裝

Mac 安裝方式
  1. 官網下載安裝包dmg便可
  2. 安裝
  3. 偏好設置啓動mysql
  4. 配置bash_profile
  5. 添加「export PATH=$PATH:/usr/local/mysql/bin」

下載MySQL驅動 JDBChtml

1.2 建立項目

IDEA選擇: Java Enterprise -> Web application
配置項目:java

  1. WEB_INF 內建立 classes 和 lib 文件夾
  2. File -> Project Structure -> paths -> Use module compile output path 選擇classes文件夾
  3. File -> Project Structure -> Dependecies -> 「+」號 -> JAR… -> 選擇建立的lib文件夾

1.3 數據庫建立

開啓終端:登陸數據庫mysql

mysql -u root -p

建立一個新的數據庫 -> shopping :web

create database shopping;

查看是否建立成功:sql

show databases;

1.4 鏈接數據庫測試

IDEA: View -> Tool Windows -> Database數據庫

  • : 選擇 Data Source -> MySQL

Database:shopping
再填寫用戶名+密碼,Test Connection數組

1.5 建立數據庫內容

1. 打開 Navicat,進入shopping數據庫

2. Query 選擇 New Query

複製粘貼:bash

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(50) default NULL,
  `city` varchar(50) default NULL,
  `price` int(11) default NULL,
  `number` int(11) default NULL,
  `picture` varchar(500) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '沃特籃球鞋', '佛山', '180', '500', '001.jpg');
INSERT INTO `items` VALUES ('2', '安踏運動鞋', '福州', '120', '800', '002.jpg');
INSERT INTO `items` VALUES ('3', '耐克運動鞋', '廣州', '500', '1000', '003.jpg');
INSERT INTO `items` VALUES ('4', '阿迪達斯T血衫', '上海', '388', '600', '004.jpg');
INSERT INTO `items` VALUES ('5', '李寧文化衫', '廣州', '180', '900', '005.jpg');
INSERT INTO `items` VALUES ('6', '小米3', '北京', '1999', '3000', '006.jpg');
INSERT INTO `items` VALUES ('7', '小米2S', '北京', '1299', '1000', '007.jpg');
INSERT INTO `items` VALUES ('8', 'thinkpad筆記本', '北京', '6999', '500', '008.jpg');
INSERT INTO `items` VALUES ('9', 'dell筆記本', '北京', '3999', '500', '009.jpg');
INSERT INTO `items` VALUES ('10', 'ipad5', '北京', '5999', '500', '010.jpg');

運行,生成表cookie

1.5.3 刷新數據庫,查看結果

1.6 存放數據庫的圖片到Web項目

  1. 項目中web目錄下新建一個文件夾images
  2. 找10張圖片放入,命名格式」001.jpg」,」002.jgp」…

2、DBHelper類 鏈接數據庫

定義靜態變量:數據庫驅動

public static final String driver = "com.mysql.jdbc.Driver"; //數據庫驅動
//鏈接數據庫的URL地址
public static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&charactorEncoding=UTF-8";
public static final String username = "root";
public static final String password = "amoy1205";
public static Connection conn = null;

靜態代碼塊負責加載驅動,須要捕獲異常

static{
    try{
        Class.forName(driver); //加載驅動
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
}

單例模式:返回數據庫鏈接對象

public static Connection getConnection() throws Exception{
    if(conn==null){
        conn = DriverManager.getConnection(url, username, password);
        return conn;
    }
    return conn; //說明被實例化過
}

寫個方法測試是否鏈接成功:

public static void main(String[] args){
    try
    {
        Connection conn = DBHelper.getConnection();
        if(conn!=null){
            System.out.println("數據庫鏈接正常");
        }
        else {
            System.out.println("數據庫鏈接異常");
        }

    }
    catch (Exception ex){
        ex.printStackTrace();
    }
}

3、item 類(存放商品實體)

定義商品屬性 :

private int id ; //商品編號
private String name; //商品名稱
private String city; //產地
private int price;  //價格
private int number;  //庫存
private String picture; //商品圖片

4、ItemDAO 類 (業務邏輯類)

4.1 獲取所有商品信息的方法

經過SQL語句:select * from Items; 從表items查詢結果。

public ArrayList<Items> getAllItems()
{
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null; //(ResultSet)是數據中查詢結果返回的一種對象
    ArrayList<Items> list = new ArrayList<Items>();//商品集合
    try{
        conn = DBHelper.getConnection(); //鏈接數據庫
        String sql = "select * from Items;"; //SQL語句
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();
        while(rs.next())
        {
            Items item = new Items();
            item.setId(rs.getInt("id"));
            item.setName(rs.getString("name"));
            item.setCity(rs.getString("city"));
            item.setNumber(rs.getInt("number"));
            item.setPrice(rs.getInt("price"));
            item.setPicture(rs.getString("picture"));
            list.add(item); //把一個商品加入集合
        }
        return list; //返回集合
    }
    catch (Exception ex){
        ex.printStackTrace();
        return null;
    }
    finally {
        //釋放數據集對象
        if(rs!=null)
        {
            try
            {
                rs.close();
                rs = null;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
        //釋放語句對象
        if(stmt!=null)
        {
            try
            {
                stmt.close();
                stmt = null;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

執行SQL語句要記得捕獲異常,且要用finally釋放資源。

PreparedStatement : 執行SQL查詢語句的API之一
「JDBC 中preparedStatement和Statement區別」參考資料: https://blog.csdn.net/xuebing1995/article/details/72235380

4.2 根據商品編號獲取商品信息

public Items getItemsById()
和獲取所有信息的代碼差很少,這裏僅修改try{}裏的代碼:

  1. 修改sql查詢語句
  2. stmt.setInt(1,id)將指定的參數設置爲給定的java int值, sql將查詢id匹配的條目
  3. 查詢結果不用循環
  4. 返回item而不是list
try{
    conn = DBHelper.getConnection();
    String sql = "select * from Items WHERE id=?;"; //SQL語句
    stmt = conn.prepareStatement(sql);
    stmt.setInt(1,id);
    rs = stmt.executeQuery();
    if(rs.next())
    {
        Items item = new Items();
        item.setId(rs.getInt("id"));
        item.setName(rs.getString("name"));
        item.setCity(rs.getString("city"));
        item.setNumber(rs.getInt("number"));
        item.setPrice(rs.getInt("price"));
        item.setPicture(rs.getString("picture"));
        return item;
    }
    else {
        return null;
    }
}

4.3 經過cookie實現 商品瀏覽記錄DAO

① 傳入list字符串,經過分隔符」#」識別出不一樣的商品id,存放到字符串數組arr中

注意: Tomcat高版本中,Cookie對象的構造函數的兩個字符串參數:Cookie名字和Cookie值都不能包含空白字符以及下列字符:[]() < > = , " / ? @ :
所以,分隔符采用」#」

② 根據分割後的id,查詢商品信息,添加到itemlist中,返回

public ArrayList<Items> getViewList(String list){
    System.out.println("list:"+list);
    ArrayList<Items> itemlist = new ArrayList<Items>();
    int iCount = 5;
    if (list!=null && list.length()>=0)
    {
        String[] arr = list.split("#");
        System.out.println("arr.length="+arr.length);
        if(arr.length>=5)
        {
            for(int i=arr.length-1;i>=arr.length-iCount;i--)
            {
                itemlist.add(getItemsById(Integer.parseInt(arr[i])));
            }
        }
        else
        {
            for(int i=arr.length-1;i>=0;i--)
            {
                itemlist.add(getItemsById(Integer.parseInt(arr[i])));
            }
        }
        return itemlist;
    }
    else
    {
        return null;
    }
}

5、頁面層

5.1 index.jsp

5.1.1 <head> 中添加css樣式

<head>
    <title>商品展現</title>
      <style type="text/css">
          div{
              float:left;
              margin: 10px;
          }
          div dd{
              margin:0px;
              font-size:10pt;
          }
          div dd.dd_name
          {
              color:blue;
          }
          div dd.dd_city
          {
              color:#000;
          }
      </style>
  </head>

5.1.2 獲取所有商品信息

調用ItemsDAO的getAllItems() 得到全部商品的Item實例

遍歷打印商品信息:

<h1>商品展現</h1>
    <hr>
    <table>
        <tr>
            <td>
                <!-- 商品循環開始 -->
                <%
                    ItemsDAO itemsDao = new ItemsDAO();
                    ArrayList<Items> list = itemsDao.getAllItems();
                    if(list!=null&&list.size()>0)
                    {
                        for(int i=0;i<list.size();i++)
                        {
                            Items item = list.get(i);
                %>
                <div>
                    <dl>
                        <dt>
                            <a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
                        </dt>
                        <dd class="dd_name"><%=item.getName() %></dd>
                        <dd class="dd_city">產地:<%=item.getCity() %>&nbsp;&nbsp;價格:¥ <%=item.getPrice() %></dd>
                    </dl>
                </div>
                <!-- 商品循環結束 -->
                <%
                        }
                    }
                %>
            </td>
        </tr>
    </table>
爲圖片設置超連接,目的:進入到商品詳情頁面

5.2 details.jsp

實現功能:顯示商品詳情(點取超連接時傳入的id值再調用ItemsDAO的getItemsById()獲取商品信息)+最近瀏覽商品記錄(cookie實現)

css樣式和index.jsp相同,複製便可

<body>中須要處理的:
① 從request中獲取cookie: request.getCookies()
② 獲取本項目Cookie對應的字符串

if(c.getName().equals("ListViewCookie"))
  {
     list = c.getValue();
  }

③ 追加本次瀏覽的記錄:

list+=request.getParameter("id")+"#";

④ 建立新的cookie對象,並將其放到response:

Cookie cookie = new Cookie("ListViewCookie",list);
  response.addCookie(cookie);

⑤ 再經過ItemsDAO的getViewList()獲取cookie的字符串,根據返回的列表打印最近瀏覽的記錄

<body>標籤中添加完整代碼:

<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>
      <% 
        }
      %>
      <% 
          String list ="";
          //從客戶端得到Cookies集合
          Cookie[] cookies = request.getCookies();
          //遍歷這個Cookies集合
          if(cookies!=null&&cookies.length>0)
          {
              for(Cookie c:cookies)
              {
                  if(c.getName().equals("ListViewCookie"))
                  {
                     list = c.getValue();
                  }
              }
          }
          
          list+=request.getParameter("id")+"#";
          //若是瀏覽記錄超過1000條,清零.
          String[] arr = list.split("#");
          if(arr!=null&&arr.length>0)
          {
              if(arr.length>=1000)
              {
                  list="";
              }
          }
          Cookie cookie = new Cookie("ListViewCookie",list);
          response.addCookie(cookie);
      
      %>
      <!-- 瀏覽過的商品 -->
      <td width="30%" bgcolor="#EEE" align="center">
         <br>
         <b>您瀏覽過的商品</b><br>
         <!-- 循環開始 -->
         <% 
            ArrayList<Items> itemlist = itemDao.getViewList(list);
            if(itemlist!=null&&itemlist.size()>0 )
            {
               System.out.println("itemlist.size="+itemlist.size());
               for(Items i:itemlist)
               {
                     
         %>
         <div>
         <dl>
           <dt>
             <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
           </dt>
           <dd class="dd_name"><%=i.getName() %></dd> 
           <dd class="dd_city">產地:<%=i.getCity() %>&nbsp;&nbsp;價格:<%=i.getPrice() %> ¥ </dd> 
         </dl>
         </div>
         <% 
               }
            }
         %>
         <!-- 循環結束 -->
      </td>
    </tr>
  </table>
相關文章
相關標籤/搜索