一個項目執行個體(JDBC,Cookie的使用)

來源:互聯網
上載者:User

標籤:pad   resultset   oca   cin   nec   encoding   mod   body   arraylist   

採用Model1(JSP+javabean)來實現步驟:
  1. dbHelper是建立資料庫的連結化物件,操作資料庫JDBC
  2. 建立實體類:商品類
  3. 建立商務邏輯類(DAO)
  4. 建立頁面層(也可以放在第一步)

商務邏輯類中包括:

  • 查詢所有商品 
  • 查詢指定商品等

 

項目原型

items.sql是我們要用到的資料庫表。是寫好的,直接匯入資料庫中就行

介面圖:

 

 

DBHelper類的設計

吧jar包放進來  

連結mysql的驅動

 

 

 

中文亂碼的時候,在Idea右下角,選擇GBK然後reload即可,因為預設的是UTF-8

 

 

DBHelper

package util;import java.sql.Connection;import java.sql.DriverManager;public class DBHelper {       private static final String driver = "com.mysql.jdbc.Driver"; //資料庫驅動    //串連資料庫的URL地址    private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";     private static final String username="root";//資料庫的使用者名稱    private static final String password="123456";//資料庫的密碼        private static Connection conn=null;        //靜態代碼塊負責載入驅動    static     {        try        {            Class.forName(driver);        }        catch(Exception ex)        {            ex.printStackTrace();        }    }        //單例模式返回資料庫連接對象    public static Connection getConnection() throws Exception    {        if(conn==null)//如果conn不存在就建立一個        {            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();        }            }}

  資料庫中建好shopping這個scheme

然後將items.sql匯入。

 

   寫一個main方法測試一下是否連結正常

 

實體類

 

 

編寫的欄位名字最好跟資料庫中的欄位名字相同

 

package entity;//商品類public class Items {    private int id; // 商品編號    private String name; // 商品名稱    private String city; // 產地    private int price; // 價格    private int number; // 庫存    private String picture; // 商品圖片    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public int getPrice() {        return price;    }    public void setPrice(int price) {        this.price = price;    }    public int getNumber() {        return number;    }    public void setNumber(int number) {        this.number = number;    }    public String getPicture() {        return picture;    }    public void setPicture(String picture) {        this.picture = picture;    }}

 

接下來設計資料訪問層也就是DAO層

建立商務邏輯類(DAO)

獲得所有的商品資訊,並在頁面上顯示

以下三個類重點

  • Connection
  • PreparedStatement
  • ResultSet
package dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import util.DBHelper;import entity.Items;//商品的商務邏輯類public class ItemsDAO {    // 獲得所有的商品資訊    public ArrayList<Items> getAllItems() {        Connection conn = null;        PreparedStatement stmt = null;        ResultSet rs = null;        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();                }            }        }    }}

商務邏輯層寫好後,下面要做的就是在頁面上來顯示就可以了

展示所有商品

在index.jsp中(只貼出了body標籤中的內容),這時候還麼有去寫jsp代碼,僅僅是html頁面

<body>    <h1>商品展示</h1>    <hr>      <center>    <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">      <tr>        <td>                    <!-- 商品迴圈開始 ,裡面的屬性值需要等下動態從資料庫擷取-->           <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>    </center>  </body>

加入jsp代碼後(標紅的部分):

 <body>    <h1>商品展示</h1>    <hr>      <center>    <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">      <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>    </center>  </body>

 

一個項目執行個體(JDBC,Cookie的使用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.