程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> jsp+servlet+jdbc實現對數據庫的增刪改查

jsp+servlet+jdbc實現對數據庫的增刪改查

編輯:關於JSP

一、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  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 
     
  } 
   
 
} 

源代碼下載鏈接

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved