当前位置:   article > 正文

实验五~JDBC数据库访问与DAO设计模式

实验五~JDBC数据库访问与DAO设计模式

1. 使用传统JDBC方法与Model 1模型通过JSP页面访问数据库。

【步骤1】在MySQL数据库test中创建books表,其结构如下:

创建数据库MySQL代码与插入数据代码

  1. drop database if exists web_test;
  2. create database web_test character set utf8mb4;
  3. use web_test;
  4. create table books(
  5. book_id varchar(10) not null,
  6. title varchar(50),
  7. author varchar(20),
  8. publisher varchar(40),
  9. price float
  10. );
  11. insert into books values ('204', 'Head First Servlets & JSP', 'Bryan Basham', '中国电力出版社', 98);
  12. insert into books values ('201', 'Servlets与JSP核心教程', 'Hall Marty', '清华大学出版社', 45);
  13. insert into books values ('202', 'Tomcat与Java Web 开发技术详解', '孙卫琴', '机械工业出版社', 45);
  14. insert into books values ('203', 'JSP 应用开发技术', '柳永坡', '人民邮电出版社', 52);
  15. insert into books values ('205', 'J2EE 1.4 编程指南', 'Spielman Sue', '电子工业出版社', 68);

 【步骤2】创建模型:编写名称为BookBean.java的JavaBean用于封装图书的信息;编写BookDAO.java,采用传统JDBC方法创建数据库连接,对图书信息进行查询。

DBUtil的代码 

  1. package org.example.utils;
  2. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  3. import javax.sql.DataSource;
  4. import java.sql.Connection;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. public class DBUtil {
  9. private static volatile DataSource DS;
  10. private static DataSource getDataSource() {
  11. if (DS == null) {
  12. synchronized (DBUtil.class) {
  13. if (DS == null) {
  14. MysqlDataSource dataSource = new MysqlDataSource();
  15. dataSource.setURL("jdbc:mysql://localhost:3306/web_test");
  16. dataSource.setUser("root");//账号
  17. dataSource.setPassword("142516");
  18. dataSource.setUseSSL(false);//不设置不会出现问题,但会出现红色警告
  19. //数据库的编码格式,可以设置为UTF-8,或是utf8
  20. dataSource.setCharacterEncoding("utf8");
  21. DS = dataSource;
  22. }
  23. }
  24. }
  25. return DS;
  26. }
  27. //获取数据库连接
  28. public static Connection getConnection() {
  29. try {
  30. return getDataSource().getConnection();
  31. } catch (SQLException e) {
  32. throw new RuntimeException("获取数据库连接异常", e);
  33. }
  34. }
  35. //释放连接
  36. public static void close(java.sql.Connection c, Statement s, ResultSet rs) {
  37. try {
  38. if(rs != null) rs.close();
  39. if(s != null) s.close();
  40. if(c != null) c.close();
  41. } catch (SQLException e) {
  42. throw new RuntimeException("jdbc释放资源出错", e);
  43. }
  44. }
  45. }

上面这部分需要改一下

BookBean代码 

  1. package org.example.beans;
  2. public class BookBean {
  3. private String bookId;
  4. private String title;
  5. private String author;
  6. private String publisher;
  7. private double price;
  8. public String getBookId() {
  9. return bookId;
  10. }
  11. public void setBookId(String bookId) {
  12. this.bookId = bookId;
  13. }
  14. public String getTitle() {
  15. return title;
  16. }
  17. public void setTitle(String title) {
  18. this.title = title;
  19. }
  20. public String getAuthor() {
  21. return author;
  22. }
  23. public void setAuthor(String author) {
  24. this.author = author;
  25. }
  26. public String getPublisher() {
  27. return publisher;
  28. }
  29. public void setPublisher(String publisher) {
  30. this.publisher = publisher;
  31. }
  32. public double getPrice() {
  33. return price;
  34. }
  35. public void setPrice(double price) {
  36. this.price = price;
  37. }
  38. }

BookDao代码 

  1. package org.example.dao;
  2. import org.example.beans.BookBean;
  3. import org.example.utils.DBUtil;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. public class BookDao {
  10. public static List<BookBean> queryBooks() {
  11. Connection c = null;
  12. PreparedStatement ps = null;
  13. ResultSet rs = null;
  14. try {
  15. c = DBUtil.getConnection();
  16. String sql = "select * from books";
  17. ps = c.prepareStatement(sql);
  18. rs = ps.executeQuery();
  19. List<BookBean> books = new ArrayList<>();
  20. while (rs.next()) {
  21. BookBean b = new BookBean();
  22. b.setBookId(rs.getString("book_id"));
  23. b.setAuthor(rs.getString("author"));
  24. b.setTitle(rs.getString("title"));
  25. b.setPublisher(rs.getString("publisher"));
  26. b.setPrice(rs.getDouble("price"));
  27. books.add(b);
  28. }
  29. return books;
  30. } catch (Exception e) {
  31. throw new RuntimeException("查询books出错", e);
  32. } finally {
  33. DBUtil.close(c, ps, rs);
  34. }
  35. }
  36. }

【步骤3】创建兼具视图与控制器功能的JSP页面:编写displayBooks.jsp页面,使用<jsp:useBean>动作调用BookDAO查询所有图书的信息,以表格的形式显示所有图书的书号、书名、作者、价格和出版社名称。

displayBooks.jsp 

  1. <%@ page import="java.util.*" %>
  2. <%@ page import="org.example.beans.*" %>
  3. <%@ page contentType="text/html;charset=utf-8" %>
  4. <jsp:useBean id="book" class="org.example.dao.BookDao" scope="session"/>
  5. <html>
  6. <head>
  7. <title>displayBooks</title>
  8. <style>
  9. td{
  10. text-align: center;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <table width="500" height="256" border="1" align="center">
  16. <tr>
  17. <th scope="col">bookid</th>
  18. <th scope="col">title</th>
  19. <th scope="col">author</th>
  20. <th scope="col">publisher</th>
  21. <th scope="col">price</th>
  22. </tr>
  23. <%
  24. List<BookBean> books = book.queryBooks();
  25. int len = books.size();
  26. for (int i = 0; i < len; i++) {
  27. String book_id = books.get(i).getBookId();
  28. String title = books.get(i).getTitle();
  29. String author = books.get(i).getAuthor();
  30. String publisher = books.get(i).getPublisher();
  31. double price = books.get(i).getPrice();
  32. %>
  33. <tr>
  34. <td><%=book_id%> </td>
  35. <td><%=title%></td>
  36. <td><%=author%></td>
  37. <td><%=publisher%></td>
  38. <td><%=price%></td>
  39. </tr>
  40. <% } %>
  41. </table>
  42. </body>
  43. </html>

 2. 基于实验内容1创建的数据库表和模型,采用MVC设计模式,通过数据源和DAO对象访问数据库。其中JavaBeans实现模型与数据库访问与操作,Servlet实现控制器,JSP页面实现视图。

  • 模型包括2个JavaBean:BookBean用于存放图书信息,BookDAO用于访问数据库。

 BookBean.java(BookBean与上面的BookBean一样)

  1. package org.example.beans;
  2. import java.io.Serializable;
  3. /**
  4. * Created with IntelliJ IDEA.
  5. * Description:
  6. * User: Li_yizYa
  7. * Date: 2023—04—24
  8. * Time: 17:57
  9. */
  10. //@SuppressWarnings("serial")
  11. public class BookBean {
  12. private String bookId;
  13. private String title;
  14. private String author;
  15. private String publisher;
  16. private double price;
  17. public String getBookId() {
  18. return bookId;
  19. }
  20. public void setBookId(String bookId) {
  21. this.bookId = bookId;
  22. }
  23. public String getTitle() {
  24. return title;
  25. }
  26. public void setTitle(String title) {
  27. this.title = title;
  28. }
  29. public String getAuthor() {
  30. return author;
  31. }
  32. public void setAuthor(String author) {
  33. this.author = author;
  34. }
  35. public String getPublisher() {
  36. return publisher;
  37. }
  38. public void setPublisher(String publisher) {
  39. this.publisher = publisher;
  40. }
  41. public double getPrice() {
  42. return price;
  43. }
  44. public void setPrice(double price) {
  45. this.price = price;
  46. }
  47. }

 BookDao.java(BookDao在上面的java文件中额外加了几个方法)

  1. package org.example.dao;
  2. import org.example.beans.BookBean;
  3. import org.example.utils.DBUtil;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. /**
  10. * Created with IntelliJ IDEA.
  11. * Description:
  12. * User: Li_yizYa
  13. * Date: 2023—04—24
  14. * Time: 18:13
  15. */
  16. public class BookDao {
  17. public static List<BookBean> queryBooks() {
  18. Connection c = null;
  19. PreparedStatement ps = null;
  20. ResultSet rs = null;
  21. try {
  22. c = DBUtil.getConnection();
  23. String sql = "select * from books";
  24. ps = c.prepareStatement(sql);
  25. rs = ps.executeQuery();
  26. List<BookBean> books = new ArrayList<>();
  27. while (rs.next()) {
  28. BookBean b = new BookBean();
  29. b.setBookId(rs.getString("book_id"));
  30. b.setAuthor(rs.getString("author"));
  31. b.setTitle(rs.getString("title"));
  32. b.setPublisher(rs.getString("publisher"));
  33. b.setPrice(rs.getDouble("price"));
  34. books.add(b);
  35. }
  36. return books;
  37. } catch (Exception e) {
  38. throw new RuntimeException("查询books出错", e);
  39. } finally {
  40. DBUtil.close(c, ps, rs);
  41. }
  42. }
  43. //根据序号查询
  44. public static BookBean queryById(String id) {
  45. Connection c = null;
  46. PreparedStatement ps = null;
  47. ResultSet rs = null;
  48. BookBean b = null;
  49. try {
  50. c = DBUtil.getConnection();
  51. String sql = "select * from books where book_id = ?";
  52. ps = c.prepareStatement(sql);
  53. ps.setString(1, id);
  54. rs = ps.executeQuery();
  55. while (rs.next()) {
  56. b = new BookBean();
  57. b.setBookId(rs.getString("book_id"));
  58. b.setAuthor(rs.getString("author"));
  59. b.setTitle(rs.getString("title"));
  60. b.setPublisher(rs.getString("publisher"));
  61. b.setPrice(rs.getDouble("price"));
  62. }
  63. return b;
  64. } catch (Exception e) {
  65. throw new RuntimeException("查询books出错", e);
  66. } finally {
  67. DBUtil.close(c, ps, rs);
  68. }
  69. }
  70. //根据书名查询
  71. public static BookBean queryByTitle(String title) {
  72. Connection c = null;
  73. PreparedStatement ps = null;
  74. ResultSet rs = null;
  75. BookBean b = null;
  76. try {
  77. c = DBUtil.getConnection();
  78. String sql = "select * from books where title = ?";
  79. ps = c.prepareStatement(sql);
  80. ps.setString(1, title);
  81. rs = ps.executeQuery();
  82. while (rs.next()) {
  83. b = new BookBean();
  84. b.setBookId(rs.getString("book_id"));
  85. b.setAuthor(rs.getString("author"));
  86. b.setTitle(rs.getString("title"));
  87. b.setPublisher(rs.getString("publisher"));
  88. b.setPrice(rs.getDouble("price"));
  89. }
  90. return b;
  91. } catch (Exception e) {
  92. throw new RuntimeException("查询books出错", e);
  93. } finally {
  94. DBUtil.close(c, ps, rs);
  95. }
  96. }
  97. //根据作者查询
  98. public static BookBean queryByAuthor(String author) {
  99. Connection c = null;
  100. PreparedStatement ps = null;
  101. ResultSet rs = null;
  102. BookBean b = null;
  103. try {
  104. c = DBUtil.getConnection();
  105. String sql = "select * from books where author = ?";
  106. ps = c.prepareStatement(sql);
  107. ps.setString(1, author);
  108. rs = ps.executeQuery();
  109. while (rs.next()) {
  110. b = new BookBean();
  111. b.setBookId(rs.getString("book_id"));
  112. b.setAuthor(rs.getString("author"));
  113. b.setTitle(rs.getString("title"));
  114. b.setPublisher(rs.getString("publisher"));
  115. b.setPrice(rs.getDouble("price"));
  116. }
  117. return b;
  118. } catch (Exception e) {
  119. throw new RuntimeException("查询books出错", e);
  120. } finally {
  121. DBUtil.close(c, ps, rs);
  122. }
  123. }
  124. //插入数据
  125. public static int insert(BookBean book) {
  126. Connection c = null;
  127. PreparedStatement ps = null;
  128. try {
  129. c = DBUtil.getConnection();
  130. String sql = "insert into books values (?, ?, ?, ?, ?);";
  131. ps = c.prepareStatement(sql);
  132. ps.setString(1, book.getBookId());
  133. ps.setString(2, book.getTitle());
  134. ps.setString(3, book.getAuthor());
  135. ps.setString(4, book.getPublisher());
  136. ps.setDouble(5, book.getPrice());
  137. return ps.executeUpdate();
  138. } catch (Exception e) {
  139. throw new RuntimeException("插入books出错", e);
  140. } finally {
  141. DBUtil.close(c, ps, null);
  142. }
  143. }
  144. }

  • 控制器包括2个Servlet:BookQueryServlet根据请求参数查询图书信息、BookInsertServlet用来向数据库中插入一条图书信息。

BookQueryServlet.java

  1. package org.example.servlet;
  2. import org.example.beans.BookBean;
  3. import org.example.dao.BookDao;
  4. import javax.servlet.RequestDispatcher;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.io.IOException;
  11. /**
  12. * Created with IntelliJ IDEA.
  13. * Description:
  14. * User: Li_yizYa
  15. * Date: 2023—04—24
  16. * Time: 20:12
  17. */
  18. @WebServlet("/query")
  19. public class BookQueryServlet extends HttpServlet {
  20. @Override
  21. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  22. resp.setCharacterEncoding("utf-8");
  23. String selection = req.getParameter("selection");
  24. String content = req.getParameter("content");
  25. BookBean book = null;
  26. if (selection.equals("book_id")) {
  27. book = BookDao.queryById(content);
  28. } else if (selection.equals("title")) {
  29. book = BookDao.queryByTitle(content);
  30. } else {
  31. book = BookDao.queryByAuthor(content);
  32. }
  33. if(book!=null){
  34. req.getSession().setAttribute("book", book);
  35. RequestDispatcher view = req.getRequestDispatcher("display.jsp");
  36. view.forward(req, resp);
  37. }else{
  38. RequestDispatcher view = req.getRequestDispatcher("errorPage.jsp");
  39. view.forward(req, resp);
  40. }
  41. }
  42. }

BookInsertServlet.java

  1. package org.example.servlet;
  2. import org.example.beans.BookBean;
  3. import org.example.dao.BookDao;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.IOException;
  10. import java.io.PrintWriter;
  11. import java.util.Date;
  12. /**
  13. * Created with IntelliJ IDEA.
  14. * Description:
  15. * User: Li_yizYa
  16. * Date: 2023—04—24
  17. * Time: 20:12
  18. */
  19. @WebServlet("/insert")
  20. public class BookInsertServlet extends HttpServlet {
  21. @Override
  22. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. req.setCharacterEncoding("utf-8");
  24. resp.setContentType("text/html;charset=utf-8");
  25. BookBean book = new BookBean();
  26. book.setBookId(req.getParameter("bookId"));
  27. book.setTitle(req.getParameter("title"));
  28. book.setAuthor(req.getParameter("author"));
  29. book.setPublisher(req.getParameter("publisher"));
  30. book.setPrice(Double.parseDouble(req.getParameter("price")));
  31. System.out.println(book.getTitle());
  32. int ret = BookDao.insert(book);
  33. String respContent = "插入失败";
  34. if (ret == 1) {
  35. respContent = "插入成功";
  36. }
  37. PrintWriter out = resp.getWriter();
  38. out.println("<HTML>");
  39. out.println(" <BODY><center>");
  40. out.println("<h2>"+respContent + "</h2>");
  41. out.println(" </center> </BODY>");
  42. out.println("</HTML>");
  43. }
  44. }

  • 视图包括4个JSP页面:bookQuery.jsp显示图书查询表单的页面、bookInsert.jsp显示收集图书信息表单的页面、display.jsp显示查询结果页面、errorPage.jsp显示查询错误页面。

bookQuery.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <head>
  3. <title>bookQuery</title>
  4. </head>
  5. <body>
  6. <form action="query" method="post">
  7. 请做选择:<select name="selection">
  8. <option value="book_id">序号</option>
  9. <option value="title">书名</option>
  10. <option value="author">作者</option>
  11. </select>
  12. <br>
  13. 查询内容:<input type="text" name="content">
  14. <input type="submit" value="查询">
  15. </form>
  16. </body>
  17. </html>

bookInsert.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <jsp:useBean id="book" class="org.example.beans.BookBean" scope="session"/>
  3. <html>
  4. <head>
  5. <title>bookInsert</title>
  6. </head>
  7. <body>
  8. <h3>请输入图书信息:</h3>
  9. <form action="insert" method="post">
  10. <table>
  11. <tr><td>书号</td> <td><input type="text" name="bookId" ></td></tr>
  12. <tr><td>书名</td><td><input type="text" name="title"></td></tr>
  13. <tr><td>作者</td><td><input type="text" name="author" ></td></tr>
  14. <tr><td>出版社</td><td><input type="text" name="publisher" ></td></tr>
  15. <tr><td>单价</td><td><input type="text" name="price" ></td></tr>
  16. <tr><td><input type="submit" value="确定" ></td>
  17. <td><input type="reset" value="重置" ></td>
  18. </tr>
  19. </table>
  20. </form>
  21. </body>
  22. </html>

display.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <jsp:useBean id="book" class="org.example.beans.BookBean" scope="session"/>
  3. <jsp:setProperty name="book" property="*"/>
  4. <html>
  5. <head>
  6. <title>display</title>
  7. </head>
  8. <body>
  9. 书号:<jsp:getProperty name="book" property="bookId"/><br><br>
  10. 书名:<jsp:getProperty name="book" property="title"/><br><br>
  11. 作者:<jsp:getProperty name="book" property="author"/><br><br>
  12. 出版社:<jsp:getProperty name="book" property="publisher"/><br><br>
  13. 价格:<jsp:getProperty name="book" property="price"/><br><br>
  14. </body>
  15. </html>

errorPage.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>errorPage</title>
  5. </head>
  6. <body>
  7. Sorry,未查询到您需要的图书!
  8. </body>
  9. </html>

3. DAO设计模式练习。 

【步骤1】:使用root用户登录MySQL的test数据库,创建customer表,包括custName、email、phone等字段,设计CustomerBean传输对象,使其实现java.io.Serializable接口。

创建数据库代码

  1. create table customer(
  2. custName varchar(20),
  3. email varchar(40),
  4. phone varchar(20)
  5. );

 CustomerBean.java

  1. package org.example.beans;
  2. import java.io.Serializable;
  3. /**
  4. * Created with IntelliJ IDEA.
  5. * Description:
  6. * User: Li_yizYa
  7. * Date: 2023—04—24
  8. * Time: 21:49
  9. */
  10. @SuppressWarnings("serial")
  11. public class CustomerBean implements Serializable {
  12. private String custName;
  13. private String email;
  14. private String phone;
  15. public String getCustName() {
  16. return custName;
  17. }
  18. public void setCustName(String custName) {
  19. this.custName = custName;
  20. }
  21. public String getEmail() {
  22. return email;
  23. }
  24. public void setEmail(String email) {
  25. this.email = email;
  26. }
  27. public String getPhone() {
  28. return phone;
  29. }
  30. public void setPhone(String phone) {
  31. this.phone = phone;
  32. }
  33. }

【步骤2】:创建CustomerDAO类实现数据库访问逻辑,通过该类可以获得一个连接对象,对数据库进行查询、插入、修改和删除操作,最后关闭指定的对象。

  1. package org.example.dao;
  2. import org.example.beans.BookBean;
  3. import org.example.beans.CustomerBean;
  4. import org.example.utils.DBUtil;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * Created with IntelliJ IDEA.
  13. * Description:
  14. * User: Li_yizYa
  15. * Date: 2023—04—24
  16. * Time: 21:57
  17. */
  18. public class CustomerDAO {
  19. public static CustomerBean queryByName(String name) {
  20. Connection c = null;
  21. PreparedStatement ps = null;
  22. ResultSet rs = null;
  23. try {
  24. System.out.println(name);
  25. c = DBUtil.getConnection();
  26. String sql = "select * from customer where custName = ?";
  27. ps = c.prepareStatement(sql);
  28. ps.setString(1, name);
  29. rs = ps.executeQuery();
  30. CustomerBean customer = null;
  31. while (rs.next()) {
  32. customer = new CustomerBean();
  33. customer.setCustName(rs.getString("custName"));
  34. customer.setEmail(rs.getString("email"));
  35. customer.setPhone(rs.getString("phone"));
  36. }
  37. return customer;
  38. } catch (Exception e) {
  39. throw new RuntimeException("查询customer出错", e);
  40. } finally {
  41. DBUtil.close(c, ps, rs);
  42. }
  43. }
  44. //查询数据
  45. public static List<CustomerBean> queryCustomer() {
  46. Connection c = null;
  47. PreparedStatement ps = null;
  48. ResultSet rs = null;
  49. try {
  50. c = DBUtil.getConnection();
  51. String sql = "select * from customer";
  52. ps = c.prepareStatement(sql);
  53. rs = ps.executeQuery();
  54. List<CustomerBean> customers = new ArrayList<>();
  55. while (rs.next()) {
  56. CustomerBean customer = new CustomerBean();
  57. customer.setCustName(rs.getString("custName"));
  58. customer.setEmail(rs.getString("email"));
  59. customer.setPhone(rs.getString("phone"));
  60. customers.add(customer);
  61. }
  62. return customers;
  63. } catch (Exception e) {
  64. throw new RuntimeException("查询customer出错", e);
  65. } finally {
  66. DBUtil.close(c, ps, rs);
  67. }
  68. }
  69. //插入数据
  70. public static int insert(CustomerBean customer) {
  71. Connection c = null;
  72. PreparedStatement ps = null;
  73. try {
  74. c = DBUtil.getConnection();
  75. String sql = "insert into customer values (?, ?, ?);";
  76. ps = c.prepareStatement(sql);
  77. ps.setString(1, customer.getCustName());
  78. ps.setString(2, customer.getEmail());
  79. ps.setString(3, customer.getPhone());
  80. return ps.executeUpdate();
  81. } catch (Exception e) {
  82. throw new RuntimeException("插入books出错", e);
  83. } finally {
  84. DBUtil.close(c, ps, null);
  85. }
  86. }
  87. //根据name删除数据
  88. public static int delete(String name) {
  89. Connection c = null;
  90. PreparedStatement ps = null;
  91. try {
  92. c = DBUtil.getConnection();
  93. String sql = "delete from customer where custName=?";
  94. ps = c.prepareStatement(sql);
  95. ps.setString(1, name);
  96. return ps.executeUpdate();
  97. } catch (SQLException e) {
  98. throw new RuntimeException("删除数据库图片出错", e);
  99. } finally {
  100. DBUtil.close(c, ps, null);
  101. }
  102. }
  103. //修改数据
  104. public static int update(CustomerBean customer) {
  105. Connection c = null;
  106. PreparedStatement ps = null;
  107. try {
  108. c = DBUtil.getConnection();
  109. String sql = "update customer set custName=?,email=?,phone=? where custName = ?";
  110. ps = c.prepareStatement(sql);
  111. ps.setString(1, customer.getCustName());
  112. ps.setString(2, customer.getEmail());
  113. ps.setString(3, customer.getPhone());
  114. ps.setString(4, customer.getCustName());
  115. return ps.executeUpdate();
  116. } catch (SQLException e) {
  117. throw new RuntimeException("修改数据异常", e);
  118. } finally {
  119. DBUtil.close(c, ps, null);
  120. }
  121. }
  122. }

【步骤3】:创建insertCustomer.jsp页面,通过一个表单录入向数据库中插入的数据。

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>insertCustomer</title>
  5. </head>
  6. <body>
  7. <h3>请输入顾客信息:</h3>
  8. <form action = "insertCustomer" method = "post">
  9. <table>
  10. <tr><td>姓名</td> <td><input type="text" name="custName" ></td></tr>
  11. <tr><td>邮箱</td><td><input type="text" name="email"></td></tr>
  12. <tr><td>电话</td><td><input type="text" name="phone" ></td></tr>
  13. <tr><td><input type="submit" value="确定" ></td>
  14. <td><input type="reset" value="重置" ></td>
  15. </tr>
  16. </table>
  17. </form>
  18. </body>
  19. </html>

【步骤4】:创建InsertCustomerServlet.java控制器,调用CustomerDAO对象和传输对象,将数据插入到数据库中。

  1. package org.example.servlet;
  2. import org.example.beans.BookBean;
  3. import org.example.beans.CustomerBean;
  4. import org.example.dao.BookDao;
  5. import org.example.dao.CustomerDAO;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. /**
  14. * Created with IntelliJ IDEA.
  15. * Description:
  16. * User: Li_yizYa
  17. * Date: 2023—04—24
  18. * Time: 21:56
  19. */
  20. @WebServlet("/insertCustomer")
  21. public class InsertCustomerServlet extends HttpServlet {
  22. @Override
  23. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  24. req.setCharacterEncoding("utf-8");
  25. resp.setContentType("text/html;charset=utf-8");
  26. CustomerBean customer = new CustomerBean();
  27. customer.setCustName(req.getParameter("custName"));
  28. customer.setEmail(req.getParameter("email"));
  29. customer.setPhone(req.getParameter("phone"));
  30. int ret = CustomerDAO.insert(customer);
  31. String respContent = "插入失败";
  32. if (ret == 1) {
  33. respContent = "插入成功";
  34. }
  35. PrintWriter out = resp.getWriter();
  36. out.println("<HTML>");
  37. out.println(" <BODY><center>");
  38. out.println("<h2>"+respContent + "</h2>");
  39. out.println("<a href=\"insertCustomer.jsp\">返回添加页面</a>");
  40. out.println("<a href=\"showCustmer.jsp\">返回显示页面</a>");
  41. out.println(" </center> </BODY>");
  42. out.println("</HTML>");
  43. }
  44. }

【步骤5】:创建showCustmer.jsp,显示所有客户的信息,每一条客户信息后面增加修改和删除超链接,编写ActionServlet.java控制器,调用DAO和传输对象实现对客户信息的删除和修改功能。

showCustmer.jsp

  1. <%@ page import="java.util.*" %>
  2. <%@ page import="org.example.beans.*" %>
  3. <%@ page contentType="text/html;charset=utf-8" %>
  4. <jsp:useBean id="customer" class="org.example.dao.CustomerDAO" scope="session"/>
  5. <html>
  6. <head>
  7. <title>showCustmer</title>
  8. <style>
  9. td{
  10. text-align: center;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <table width="500" height="256" border="1">
  16. <tr>
  17. <th scope="col">客户姓名</th>
  18. <th scope="col">邮箱</th>
  19. <th scope="col">电话号</th>
  20. <th scope="col">操作</th>
  21. </tr>
  22. <%
  23. List<CustomerBean> customers = customer.queryCustomer();
  24. int len = customers.size();
  25. for (int i = 0; i < len; i++) {
  26. String custName = customers.get(i).getCustName();
  27. String email = customers.get(i).getEmail();
  28. String phone = customers.get(i).getPhone();
  29. %>
  30. <tr>
  31. <td><%=custName%> </td>
  32. <td><%=email%></td>
  33. <td><%=phone%></td>
  34. <td>
  35. <a href="update.jsp?name=<%= custName %>">修改</a>
  36. <a href="delete1?name=<%= custName %>">删除</a>
  37. </td>
  38. </tr>
  39. <% } %>
  40. </table>
  41. </body>
  42. </html>

ActionServlet.java

  1. package org.example.servlet;
  2. import org.example.beans.CustomerBean;
  3. import org.example.dao.CustomerDAO;
  4. import javax.servlet.ServletContext;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.io.IOException;
  11. import java.io.PrintWriter;
  12. /**
  13. * Created with IntelliJ IDEA.
  14. * Description:
  15. * User: Li_yizYa
  16. * Date: 2023—04—24
  17. * Time: 22:21
  18. */
  19. @WebServlet({"/delete1", "/update1"})
  20. public class ActionServlet extends HttpServlet {
  21. @Override
  22. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. String uri = req.getRequestURI();
  24. if (uri.endsWith("/delete1")) {
  25. delete1(req, resp);
  26. }
  27. if (uri.endsWith("/update1")) {
  28. update1(req, resp);
  29. }
  30. }
  31. @Override
  32. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  33. doGet(req, resp);
  34. }
  35. private void delete1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  36. String name = req.getParameter("name");
  37. int ret = CustomerDAO.delete(name);
  38. resp.sendRedirect("showCustmer.jsp");
  39. }
  40. private void update1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  41. req.setCharacterEncoding("utf-8");
  42. resp.setContentType("text/html;charset=utf-8");
  43. CustomerBean customer = new CustomerBean();
  44. customer.setCustName(req.getParameter("custName"));
  45. customer.setEmail(req.getParameter("email"));
  46. customer.setPhone(req.getParameter("phone"));
  47. System.out.println(customer.getCustName());
  48. int ret = CustomerDAO.update(customer);
  49. String respContent = "修改失败";
  50. if (ret == 1) {
  51. respContent = "修改成功";
  52. }
  53. PrintWriter out = resp.getWriter();
  54. out.println("<HTML>");
  55. out.println(" <BODY><center>");
  56. out.println("<h2>"+respContent + "</h2>");
  57. out.println("<a href=\"showCustmer.jsp\">返回显示页面</a>");
  58. out.println(" </center> </BODY>");
  59. out.println("</HTML>");
  60. }
  61. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/575392?site
推荐阅读
相关标签
  

闽ICP备14008679号