前言:
學習Java後端開發的過程中,很多情況下都要和數據庫打交道,如何通過Java程序去訪問數據庫,成爲每一個後端開發人員必備的技能點。本文以一個簡單的
項目將數據庫(這裏使用Mysql)、JDBC、Servlet、JSP串聯起來,將其中的邏輯流暢地走一遍,由於需要用到JSP和Servlet,所以這裏建立的項目
類型是Dynamic Web Project,在此聲明:僅是自己的學習總結,如有不對的地方,還請指教,互相交流學習哈^^。
第一步 數據庫及模型層的準備(模型層)
首先,自己的電腦上需要安裝Mysql數據庫,然後再數據庫中建立自己項目中需要要到的數據庫,數據庫名爲shopping;接着在shopping數據
庫中創建數據表,表名爲goods;然後向其中添加幾條記錄;這樣,數據庫方面的準備就完成啦!接着,需要針對項目中建立的數據表,設計對應的
JavaBean,用來存儲存儲從數據庫讀取的記錄。
這裏用到的sql文件:
SET FOREIGN_KEY_CHECKS=0 ;
DROP TABLE IF EXISTS `goods` ;
CREATE TABLE `goods` (
`id` int (11 ) NOT NULL AUTO_INCREMENT,
`name` varchar (50 ) DEFAULT NULL ,
`origin` varchar (50 ) DEFAULT NULL ,
`price` int (11 ) DEFAULT NULL ,
`stock` int (11 ) DEFAULT NULL ,
PRIMARY KEY (`id` )
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
package com.model;
/**
* 與數據庫shopping中的goods數據表相對應的JavaBean
*/
public class Goods {
private int id;
private String name;
private int price;
private String origin;
private int stock;
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 int getPrice ()
{
return price;
}
public void setPrice (int price)
{
this .price = price;
}
public String getOrigin ()
{
return origin;
}
public void setOrigin (String origin)
{
this .origin = origin;
}
public int getStock ()
{
return stock;
}
public void setStock (int stock)
{
this .stock = stock;
}
}`
第二步 數據庫連接的準備(服務層)
首先,下載JDBC所用的jar包,將jar包拷貝到項目的lib文件夾下,然後右擊jar包,選擇Build Path,將jar包添加到當前項目的路徑
中;接着,進行獲取數據庫連接的代碼編寫;代碼如下所示。
package com.dbhelper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 專門用於提供數據庫連接的類
*/
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver" ;
private static final String url = "jdbc:mysql://localhost:3306/shopping" ;
private static final String user = "root" ;
private static final String password = "root" ;
private static Connection conn = null ;
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection (){
if (conn==null ) {
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
}
第三步 訪問數據庫的業務處理(服務層)
這裏,我們將訪問數據庫的業務邏輯只侷限在從數據庫中讀取響應的數據,其他的業務(如向數據庫中寫數據(增)、刪除數據(刪)、更新數據
(改))並沒有進行代碼的編寫,但是這些操作的實現所需的知識點,項目中給出的兩個業務邏輯處理方法都涵蓋,只需要將對應的sql語句做適當
的修改即可。
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.model.Goods;
import com.dbhelper.DBHelper;
/**
* 專門用於提供對數據庫進行處理的方法的類
*/
public class DBService {
private static Connection conn = DBHelper.getConnection();
public ArrayList<Goods> query () {
ArrayList<Goods> list = null ;
String sql = "select id,name,price,origin,stock from goods where 1=1" ;
PreparedStatement statement = null ;
ResultSet rs = null ;
Goods good = null ;
try {
statement = conn.prepareStatement(sql);
rs = statement.executeQuery();
if (rs==null )
{
return null ;
}
list = new ArrayList<>();
while (rs.next())
{
good = new Goods();
good.setId(rs.getInt("id" ));
good.setName(rs.getString("name" ));
good.setPrice(rs.getInt("price" ));
good.setOrigin(rs.getString("origin" ));
good.setStock(rs.getInt("stock" ));
list.add(good);
}
good = null ;
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (rs!=null )
{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null )
{
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
public Goods queryById (int id) {
Goods good = null ;
PreparedStatement statement = null ;
ResultSet rs = null ;
String sql = "select id,name,price,origin,stock from goods where id = ?" ;
try {
statement = conn.prepareStatement(sql);
statement.setInt(1 , id);
rs = statement.executeQuery();
if (rs == null )
{
return null ;
}
while (rs.next()) {
good = new Goods();
good.setId(rs.getInt("id" ));
good.setName(rs.getString("name" ));
good.setPrice(rs.getInt("price" ));
good.setOrigin(rs.getString("origin" ));
good.setStock(rs.getInt("stock" ));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (rs!=null ) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null ) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return good;
}
}
第四步 Servlet的準備(控制層)
項目中利用Servlet讀取用戶請求、調用業務處理層進行處理請求以及響應客戶的請求。
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.DBService;
import com.model.Goods;
@SuppressWarnings ("serial" )
public class ServiceServlet extends HttpServlet {
@Override
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("post請求處理中..." );
String id = request.getParameter("idnum" );
System.out.println(id);
DBService dbservice = new DBService();
Goods good = dbservice.queryById(Integer.valueOf(id));
request.setAttribute("good" , good);
request.getRequestDispatcher("/result.jsp" ).forward(request, response);
}
}
第五步 JSP的準備(視圖層)
這裏採用兩個JSP文件作爲視圖層,其中,query.jsp文件負責將客戶的請求傳送到Servlet中,由Servlet進行請求的接收、處理和響應
,這裏的響應爲將處理請求的結果傳送到另一個jsp文件,該文件(result.jsp)將處理的結果展示到jsp頁面上。
query.jsp文件:
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html >
<head >
<meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" >
<title > Insert title here</title >
</head >
<body >
<form name ="demandForm" action ="com/servlet/ServiceServlet" method ="post" >
<table >
<tr >
<td > 全部查詢</td >
<td > <input type ="submit" name ="all" id ="all" value ="全部查詢" /> </td >
</tr >
</table >
</form >
<form name ="demandForm1" action ="com/servlet/ServiceServlet" method ="post" >
<table >
<tr >
<td > id查詢</td >
<td > <input type ="text" name ="idnum" id ="idnumber" /> </td >
<td > <input type ="submit" value ="id查詢" /> </td >
</tr >
</table >
</form >
</body >
</html >
result.jsp文件:
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="com.model.Goods" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html >
<head >
<meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" >
<title > Insert title here</title >
</head >
<body >
<%
Goods good = (Goods)request .getAttribute("good" );
%>
商品id:<%=good.getId() %> <br />
商品名稱:<%=good.getName() %> <br />
商品價格:<%=good.getPrice() %> <br />
商品產地:<%=good.getOrigin() %> <br />
商品庫存:<%=good.getStock() %> <br />
</body >
</html >
總結
以上就是整個項目的思路和處理流程,採用從模型層開始,接着控制層,最後視圖層的順序完成整個項目的開發!整個項目框架已經搭建好,
但是細節有待完善,本文的目的是將整體的框架搭建出來,使整個處理流程在邏輯上能夠暢通。