一個小實例(使用JDBC,JSP在瀏覽器展示數據庫中的數據)


采用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>

 最終展示:

 

 這行一定要有,否則中文亂碼。

<%@  page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>

 




Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
這句話是從上一個頁面得到的指定的item
request.getParameter("id")傳過來的是字符串了理性所以要轉換成int類型



關於前后端的合作:前端頁面先寫死,固定排版,后面需要改變的變量,用jsp代碼替換掉即可。


免責聲明!

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



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