1. 程式人生 > >jsp+servlet+jdbc實現對資料庫的增刪改查

jsp+servlet+jdbc實現對資料庫的增刪改查

一、JSP和Servlet的簡單介紹

1、Servlet和JSP簡介:

Java開發Web應用程式時用到的技術主要有兩種,即Servlet和JSP,Servlet是在伺服器端執行的Java程式,一個被稱為Servlet容器的程式(其實就是伺服器) 負責執行Java程式,而JSP(Java Server Page)則是一個頁面, 由JSP容器負責執行.

2、Servlet和JSP的區別:

Servlet以Java程式為主, 輸出HTML程式碼時需要使用out.println函式,也就是說Java中內嵌HTML; 而JSP則以HTML頁面為主,需要寫Java程式碼時則在頁面中直接插入Java程式碼, 即HTML中內嵌Java.

3、MVC模型
 
MVC模型就是將資料、邏輯處理、使用者介面分離的一種方法
1)、M(Model, 模型):用於資料處理、邏輯處理
2)、V(View,檢視):用於顯示使用者介面
3)、C(Controller,控制器):根據客戶端的請求控制邏輯走向和畫面
 
而在Java中,MVC這三個部分則分別對應於 JavaBeans、JSP和Servlet
1)、M = JavaBeans:用於傳遞資料,擁有與資料相關的邏輯處理 
2)、V = JSP:從Model接收資料並生成HTML 
3)、C = Servlet:接收HTTP請求並控制Model和View

4、jdbc連線,可參考文章:點選開啟連結

二、程式碼演示,實現了book的新增刪除和修改功能

1、環境的配置

myeclipse+tomcat+mysql

2、Book中bean類

package example.bean.book;

public class Book {
	// 編號
	private int id;
	// 圖書名稱
	private String name;
	// 價格
	private double price;
	// 數量
	private int bookCount;
	// 作者
	private String author;

	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 double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public int getBookCount() {
		return bookCount;
	}

	public void setBookCount(int bookCount) {
		this.bookCount = bookCount;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

}
3、Servlet類

1)、FindServlet.java

package example.servlet.book;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import example.bean.book.Book;

/**
 * Servlet implementation class FindServlet
 */
public class FindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			// 載入資料庫驅動,註冊到驅動管理器
			Class.forName("com.mysql.jdbc.Driver");
			// 資料庫連線字串
			String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8";
			// 資料庫使用者名稱
			String username = "root";
			// 資料庫密碼
			String password = "";
			// 建立Connection連線
			Connection conn = DriverManager.getConnection(url, username,
					password);
			// 新增圖書資訊的SQL語句
			String sql = "select * from tb_books";
			// 獲取Statement
			Statement statement = conn.createStatement();

			ResultSet resultSet = statement.executeQuery(sql);

			List<Book> list = new ArrayList<Book>();
			while (resultSet.next()) {

				Book book = new Book();
				book.setId(resultSet.getInt("id"));
				book.setName(resultSet.getString("name"));
				book.setPrice(resultSet.getDouble("price"));
				book.setBookCount(resultSet.getInt("bookCount"));
				book.setAuthor(resultSet.getString("author"));
				list.add(book);

			}
			request.setAttribute("list", list);
			resultSet.close();
			statement.close();
			conn.close();

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

		request.getRequestDispatcher("book_list.jsp")
				.forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

2)、UpdateServlet.java類
package example.servlet.book;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateServlet
 */
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.valueOf(request.getParameter("id"));
		int bookCount = Integer.valueOf(request.getParameter("bookCount"));
		try {
			// 載入資料庫驅動,註冊到驅動管理器
			Class.forName("com.mysql.jdbc.Driver");
			// 資料庫連線字串
			String url = "jdbc:mysql://localhost:3306/db_book";
			// 資料庫使用者名稱
			String username = "root";
			// 資料庫密碼
			String password = "";
			// 建立Connection連線
			Connection conn = DriverManager.getConnection(url, username,
					password);
			// 更新SQL語句
			String sql = "update tb_books set bookcount=? where id=?";
			// 獲取PreparedStatement
			PreparedStatement ps = conn.prepareStatement(sql);
			// 對SQL語句中的第一個引數賦值
			ps.setInt(1, bookCount);
			// 對SQL語句中的第二個引數賦值
			ps.setInt(2, id);
			// 執行更新操作
			ps.executeUpdate();
			// 關閉PreparedStatement
			ps.close();
			// 關閉Connection
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 重定向到FindServlet
		response.sendRedirect("FindServlet");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

3)、DeleteServlet類
package example.servlet.book;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import example.dao.book.BookJdbcDao;
import example.dao.book.ConnectionFactory;

/**
 * Servlet implementation class DeleteServlet
 */
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.valueOf(request.getParameter("id"));
		try {
//			// 載入資料庫驅動,註冊到驅動管理器
//			Class.forName("com.mysql.jdbc.Driver");
//			// 資料庫連線字串
//			String url = "jdbc:mysql://localhost:3306/db_book";
//			// 資料庫使用者名稱
//			String username = "root";
//			// 資料庫密碼
//			String password = "";
//			// 建立Connection連線
//			Connection conn = DriverManager.getConnection(url, username,
//					password);
//			// 刪除圖書資訊的SQL語句
//			String sql = "delete from tb_books where id=?";
//			// 獲取PreparedStatement
//			PreparedStatement ps = conn.prepareStatement(sql);
//			// 對SQL語句中的第一個佔位符賦值
//			ps.setInt(1, id);
//			// 執行更新操作
//			ps.executeUpdate();
//			// 關閉PreparedStatement
//			ps.close();
//			// 關閉Connection
//			conn.close();
			BookJdbcDao bookDao=new BookJdbcDao();
			Connection conn=ConnectionFactory.getInstance().getConnection();
			bookDao.delete(conn,id);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 重定向到FindServlet
		response.sendRedirect("FindServlet");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

4、servlet訪問url對映配置:

由於客戶端是通過URL地址訪問web伺服器中的資源,所以Servlet程式若想被外界訪問,必須把servlet程式對映到一個URL地址上,這個工作在web.xml檔案中使用<servlet>元素和<servlet-mapping>元素完成,<servlet>元素用於註冊Servlet,它包含有兩個主要的子元素:<servlet-name>和<servlet-class>,分別用於設定Servlet的註冊名稱和Servlet的完整類名。 一個<servlet-mapping>元素用於對映一個已註冊的Servlet的一個對外訪問路徑,它包含有兩個子元素:<servlet-name>和<url-pattern>,分別用於指定Servlet的註冊名稱和Servlet的對外訪問路徑.另外:同一個Servlet可以被對映到多個URL上,即多個<servlet-mapping>元素的<servlet-name>子元素的設定值可以是同一個Servlet的註冊名.

eg:上例中的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JdbcConnection</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>FindServlet</display-name>
    <servlet-name>FindServlet</servlet-name>
    <servlet-class>example.servlet.book.FindServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FindServlet</servlet-name>
    <url-pattern>/FindServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>UpdateServlet</display-name>
    <servlet-name>UpdateServlet</servlet-name>
    <servlet-class>example.servlet.book.UpdateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UpdateServlet</servlet-name>
    <url-pattern>/UpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>DeleteServlet</display-name>
    <servlet-name>DeleteServlet</servlet-name>
    <servlet-class>example.servlet.book.DeleteServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DeleteServlet</servlet-name>
    <url-pattern>/DeleteServlet</url-pattern>
  </servlet-mapping>
</web-app>

5、jsp頁面

1)、index.jsp  web頁面主介面

<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="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>新增圖書資訊</title>

<script type="text/javascript">
	function check(form) {
		with (form) {
			if (name.value == "") {
				alert("圖書名稱不能為空");
				return false;
			}

			if (price.value == "") {
				alert("圖書價格不能為空");
				return false;
			}

			if (author.value == "") {
				alert("作者不能為空");
				return false;
			}

		}
	}
</script>

</head>


<body>

<form action="addbook.jsp" method="post" onsubmit="check(this)">
	<table align="center" width="450">
		<tr>
			<td align="center" colspan="2">
				<h2>新增圖書資訊</h2>
				<hr>
			</td>
		</tr>

		<tr>
			<td align="right">圖書名稱:</td>
			<td><input type="text" name="name"></td>
		</tr>

		<tr>
			<td align="right">價 格:</td>
			<td><input type="text" name="price"></td>
		</tr>

		<tr>
			<td align="right">數 量:</td>
			<td><input type="text" name="bookCount" /></td>
		</tr>

		<tr>
			<td align="right">作 者:</td>
			<td><input type="text" name="author" /></td>
		</tr>
		<tr>
			<td align="center" colspan="2"><input type="submit" value="添 加">
			</td>
		</tr>
	</table>
</form>

<h2 align="center">
	<a href="FindServlet">查詢圖書資訊</a>
</h2>

</body>
</html>

2)、addbook.jsp 新增書籍成功或者失敗後的顯示頁面
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>新增結果</title>
</head>
<body>
	<%
		request.setCharacterEncoding("utf-8");
	%>
	<jsp:useBean id="book" class="example.bean.book.Book"></jsp:useBean>
	<jsp:setProperty property="*" name="book" />
	<%
		try {
			// 載入資料庫驅動,註冊到驅動管理器
			Class.forName("com.mysql.jdbc.Driver");
			// 資料庫連線字串
			String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8";
			// 資料庫使用者名稱
			String username = "root";
			// 資料庫密碼
			String password = "";
			// 建立Connection連線
			Connection conn = DriverManager.getConnection(url, username,
					password);
			// 新增圖書資訊的SQL語句
			String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)";
			// 獲取PreparedStatement
			PreparedStatement ps = conn.prepareStatement(sql);
			// 對SQL語句中的第1個引數賦值
			ps.setString(1, book.getName());
			// 對SQL語句中的第2個引數賦值
			ps.setDouble(2, book.getPrice());
			// 對SQL語句中的第3個引數賦值
			ps.setInt(3, book.getBookCount());
			// 對SQL語句中的第4個引數賦值
			ps.setString(4, book.getAuthor());
			// 執行更新操作,返回所影響的行數
			int row = ps.executeUpdate();
			// 判斷是否更新成功
			if (row > 0) {
				// 更新成輸出資訊
				out.print("成功添加了 " + row + "條資料!");
			}
			// 關閉PreparedStatement,釋放資源
			ps.close();
			// 關閉Connection,釋放資源
			conn.close();
		} catch (Exception e) {
			out.print("圖書資訊新增失敗!");
			e.printStackTrace();
		}
	%>
	<br>
	<a href="index.jsp">返回</a>
</body>
</html>

3)、book_list.jsp 查詢所有書籍資訊的顯示頁面,以表格方式顯示

<!--<%@page import="sun.awt.SunHints.Value"%>-->
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.List"%>
<%@page import="example.bean.book.Book"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>所有圖書資訊</title>
<style type="text/css">
td {
	font-size: 12px;
}

h2 {
	margin: 0px
}
</style>
<script type="text/javascript">
	function check(form) {
		with (form) {
			if (bookCount.value == "") {
				alert("請輸入更新數量!");
				return false;
			}
			if (isNaN(bookCount.value)) {
				alert("格式錯誤!");
				return false;
			}
			return true;
		}
	}
</script>


</head>
<body>
	<table align="center" width="450" border="1" height="180"
		bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
		<tr bgcolor="white">
			<td align="center" colspan="7">
				<h2>所有圖書資訊</h2>
			</td>
		</tr>
		<tr align="center" bgcolor="#e1ffc1">
			<td><b>ID</b></td>
			<td><b>圖書名稱</b></td>
			<td><b>價格</b></td>
			<td><b>數量</b></td>
			<td><b>作者</b></td>
			<td><b>修改</b></td>
			<td><b>刪除</b></td>
		</tr>
		<%
			// 獲取圖書資訊集合
			List<Book> list = (List<Book>) request.getAttribute("list");
			// 判斷集合是否有效
			if (list == null || list.size() < 1) {
				out.print("沒有資料!");
			} else {
				// 遍歷圖書集合中的資料
				for (Book book : list) {
		%>
		<tr align="center"  bgcolor="white">
			<td><%=book.getId()%></td>
			<td><%=book.getName()%></td>
			<td><%=book.getPrice()%></td>
			<td><%=book.getBookCount()%></td>
			<td><%=book.getAuthor()%></td>
			<td >
				<form style="align:center;  background-color: gray" action="UpdateServlet" method="post"
					onsubmit="return check(this);">
					 <input type="hidden" name="id" value="<%=book.getId()%>"> <input
						type="text" name="bookCount" size="3">
				     <input type="submit" value="修改數量">
				</form>
			</td>
		    <td>
		    <a href="DeleteServlet?id=<%=book.getId()%>">刪除</a>
		    </td>


		</tr>
		<%
			}
			}
		%>
	</table>
	<h2 align="center">
		<a href="index.jsp">返回新增圖書資訊頁面</a>
	</h2>

</body>
</html>

6、jdbc簡單的封裝

1)、ConnectionFactory.java工廠類

package example.dao.book;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
	
	private String driverClassName = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8";
	private String userName = "root";
	private String password = "";
	
	private static ConnectionFactory connectionFactory=null;

	private ConnectionFactory() {
		
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public  Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(url, userName, password);
		
	}
	
	public static ConnectionFactory getInstance()
	{   
		if (null==connectionFactory) {
			connectionFactory=new ConnectionFactory();
		}
		return connectionFactory;
		
	}
	
	

}


2)、BookJdbcDao.java資料庫操作封裝類

package example.dao.book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import example.bean.book.Book;

public class BookJdbcDao {
	
	private PreparedStatement ptmt = null;
	private ResultSet rs = null;

	public BookJdbcDao() {
	}
	
	
	public void findAll(Connection conn) throws SQLException
	{
		//to do
		
	}
	
	public void delete(Connection conn, int id) throws SQLException
	{
		String sql = "delete from tb_books where id=?";
		try{
			ptmt = conn.prepareStatement(sql);
			// 對SQL語句中的第一個佔位符賦值
			ptmt.setInt(1, id);
			// 執行更新操作
			ptmt.executeUpdate();
			
		}finally{
			if (null!=ptmt) {
				ptmt.close();
			}
			
			if (null!=conn) {
				conn.close();
			}
			
		}
		
	}
	
	public void update(Connection conn, int id ,int bookcount) throws SQLException
	{
		//to do
		
	}
	

}
原始碼下載連結