当前位置:   article > 正文

JSP + Servlet + JDBC实现对数据库的增删改查_servlet+jdbc+jsp对数据库增删改查

servlet+jdbc+jsp对数据库增删改查

关于Servlet在web中的配置就不详细介绍了,这里就是介绍Servlet结合JDBC以及JSP操作数据库,关于环境的搭建前面几篇博客都详细的介绍了

一:通过JDBC项数据库添加数据

创建图书信息tb_books表,结构如图所示


创建名称为Book 的类

  1. package com.book.web3;
  2. public class Book {
  3. private int id;
  4. private String name;
  5. private double price;
  6. private int bookCount;
  7. private String author;
  8. public int getId(){
  9. return id;
  10. }
  11. public void setId(int id){
  12. this.id = id;
  13. }
  14. public String getName(){
  15. return name;
  16. }
  17. public void setName(String name){
  18. this.name = name;
  19. }
  20. public double getPrice(){
  21. return price;
  22. }
  23. public void setPrice(double price){
  24. this.price = price;
  25. }
  26. public int getBookCount(){
  27. return bookCount;
  28. }
  29. public void setBookCount(int bookCount){
  30. this.bookCount = bookCount;
  31. }
  32. public String getAuthor(){
  33. return author;
  34. }
  35. public void setAuthor(String author){
  36. this.author = author;
  37. }
  38. }

创建jdbc.jsp页面,用于添加数据的表单页面,该表单提交到jdbcresult.jsp页面处理

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <body>
  6. <form action="jdbcresult.jsp" method="post">
  7. <table align="center" border="1" width="50%" cellpadding="6">
  8. <tr>
  9. <th colspan="2" align="center" >添加图书信息</th><%--th加粗, cellpadding和android padding含义一样--%>
  10. </tr>
  11. <tr>
  12. <td align="center" >图书编号:</td>
  13. <td align="left" ><input type="text" name="id"></td>
  14. </tr>
  15. <tr>
  16. <td align="center" >图书名称:</td>
  17. <td align="left" ><input type="text" name="name"></td>
  18. </tr>
  19. <tr>
  20. <td align="center" >价        格:</td>
  21. <td align="left" ><input type="text" name="price"></td>
  22. </tr>
  23. <tr>
  24. <td align="center" >数        量:</td>
  25. <td align="left" ><input type="text" name="bookCount"></td>
  26. </tr>
  27. <tr>
  28. <td align="center" >作        者:</td>
  29. <td align="left" ><input type="text" name="author"></td>
  30. </tr>
  31. <tr>
  32. <th colspan="2" align="center" ><input type="submit" name="submit" value="添加"></th>
  33. </tr>
  34. </table>
  35. </form>
  36. </body>
  37. </html>

创建jdbcresult.jsp页面,该页面通过JDBC提交的图书信息添加到数据库

  1. <%@page import="java.sql.PreparedStatement"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3. pageEncoding="UTF-8"%>
  4. <%@page import="java.sql.Connection" %>
  5. <%@page import="java.sql.DriverManager" %>
  6. <% request.setCharacterEncoding("UTF-8"); %>
  7. <jsp:useBean id="book" class="com.book.web3.Book"></jsp:useBean>
  8. <jsp:setProperty property="*" name="book"/>
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  10. <html>
  11. <body>
  12. <%
  13. try{
  14. Class.forName("com.mysql.jdbc.Driver");
  15. String url = "jdbc:mysql://localhost:3306/student";
  16. String userName = "roots"; // 用户名
  17. String userPwd = "123456"; // 密码
  18. Connection conn = DriverManager.getConnection(url, userName, userPwd);
  19. String sql = "insert into tb_books(id,name,price,bookCount, author)values(?,?,?,?,?)";
  20. PreparedStatement ps = conn.prepareStatement(sql);
  21. ps.setInt(1, book.getId());
  22. ps.setString(2, book.getName());
  23. ps.setDouble(3, book.getPrice());
  24. ps.setInt(4, book.getBookCount());
  25. ps.setString(5, book.getAuthor());
  26. int row = ps.executeUpdate();
  27. if(row > 0){
  28. out.print("成功添加了 " + row + "条数据! ");
  29. }
  30. ps.close();
  31. conn.close();
  32. }catch(Exception e){
  33. out.print("图书信息添加失败 " + e.toString());
  34. }
  35. %>
  36. </body>
  37. </html>

在jdbcresult.jsp页面中,首先通过<jsp:useBean>实例化JavaBean的对象Book,并通过<jsp:setProperty>对Book对象中的属性赋值,<jsp:setProperty>标签中property属性的值可以设置为' * ',作用是将与表单中同名的属性值赋值给JavaBean对象中的同名属性,使用这种方式就不必对JavaBean中的属性一一进行赋值,减少代码量

结果展示:






二:查询数据

使用JDBC查询数据操作后,需要通过ResultSet对象来装载查询结果集。

创建名称为 JdbcFindServlet的Servlet对象,用于查询图书信息

  1. package com.book.web3;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. public class JdbcFindServlet extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15. /**
  16. * 构造函数
  17. */
  18. public JdbcFindServlet()
  19. {
  20. super();
  21. }
  22. /**
  23. * 初始化
  24. */
  25. public void init() throws ServletException
  26. {}
  27. /**
  28. * doGet()方法
  29. */
  30. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  31. {
  32. doPost(request, response);
  33. }
  34. /**
  35. * doPost()方法
  36. */
  37. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  38. try {
  39. Class.forName("com.mysql.jdbc.Driver");
  40. String url = "jdbc:mysql://localhost:3306/student";
  41. String userName = "roots"; // 用户名
  42. String userPwd = "123456"; // 密码
  43. Connection conn = DriverManager.getConnection(url, userName, userPwd);
  44. Statement stmt = conn.createStatement();
  45. String sql = "select * from tb_books";
  46. ResultSet rs = stmt.executeQuery(sql);
  47. List<Book> list = new ArrayList<Book>();
  48. while (rs.next()) {
  49. Book book = new Book();
  50. book.setId(rs.getInt("id"));
  51. book.setName(rs.getString("name"));
  52. book.setPrice(rs.getDouble("price"));
  53. book.setBookCount(rs.getInt("bookCount"));
  54. book.setAuthor(rs.getString("author"));
  55. list.add(book);
  56. }
  57. request.setAttribute("list", list);
  58. rs.close();
  59. stmt.close();
  60. conn.close();
  61. } catch (Exception e) {
  62. // TODO: handle exception
  63. }
  64. request.getRequestDispatcher("jdbcfindservlet.jsp").forward(request, response);
  65. }
  66. /**
  67. * 销毁
  68. */
  69. public void destroy()
  70. {
  71. super.destroy();
  72. }
  73. }

JdbcFindServlet对象在web.xml中的配置如下

  1. <servlet>
  2. <servlet-name>JdbcFindServlet</servlet-name>
  3. <servlet-class>com.book.web3.JdbcFindServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>JdbcFindServlet</servlet-name>
  7. <url-pattern>/findServlet.do</url-pattern> <!-- 根据不同的url来调用不同的servlet来进行处理。 -->
  8. </servlet-mapping>

创建jdbcfindservlet.jsp页面,用于显示查询信息,下面用的脚本处理的相关点击事件

  1. <%@page import="java.util.ArrayList"%>
  2. <%@page import="java.util.List"%>
  3. <%@page import="com.book.web3.Book"%>
  4. <%@ page language="java" contentType="text/html; charset=UTF-8"
  5. pageEncoding="UTF-8"%>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  7. <html>
  8. <head>
  9. <script type="text/javascript">
  10. function check(form) {
  11. with (form) {
  12. if (bookCount.value == "") {
  13. alert("请输入更新数量!");
  14. return false;
  15. }
  16. if (isNaN(bookCount.value)) {
  17. alert("格式错误!");
  18. return false;
  19. }
  20. return true;
  21. }
  22. }
  23. </script>
  24. </head>
  25. <body>
  26. <table id="table1" align="center" border="1" width="50%" cellpadding="6">
  27. <tr>
  28. <th colspan="6" align="center" >查询到的图书信息</th><%--th加粗, cellpadding和android padding含义一样--%>
  29. </tr>
  30. <tr>
  31. <th align="center" >ID</th>
  32. <th align="center" >图书名称</th>
  33. <th align="center" >价格</th>
  34. <th align="center" >数量</th>
  35. <th align="center" >作者</th>
  36. <th align="center" >修改数量</th>
  37. </tr>
  38. <%
  39. //获取图书信息集合
  40. List<Book> list = (List<Book>)request.getAttribute("list");
  41. if(list == null || list.size() < 1){
  42. out.print("没有数据 ");
  43. }else{
  44. for(Book book:list){
  45. %>
  46. <tr align="center">
  47. <td> <%= book.getId() %></td>
  48. <td> <%= book.getName() %></td>
  49. <td> <%= book.getPrice() %></td>
  50. <td> <%= book.getBookCount() %></td>
  51. <td> <%= book.getAuthor() %></td>
  52. <td>
  53. <form action="updateServlet.do" method="post" οnsubmit="return check(this);">
  54.     <input type="hidden" name="id" value="<%=book.getId()%>">
  55.      <input type="text" name="bookCount" size="3">
  56.     <input type="submit" value="修改数量">
  57.         </form>
  58. </td>
  59. </tr>
  60. <%
  61. }
  62. }
  63. %>
  64. </table>
  65. </body>
  66. </html>

创建程序入口界面,index.jsp页面

<a href="findServlet.do">查看所有图书</a>  //和web.xml配置下<url-pattern>一致

运行结果:



三:修改数据

在上面的查询界面中已经预留了修改的页面,修改的表单中含有两个属性id与bookCount,因此指定id作为修改条件

创建修改图书信息名称为JdbcUpdateServlet请求的Servlet对象

  1. package com.book.web3;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. public class JdbcUpdateServlet extends HttpServlet {
  11. private static final long serialVersionUID = 1L;
  12. /**
  13. * 构造函数
  14. */
  15. public JdbcUpdateServlet()
  16. {
  17. super();
  18. }
  19. /**
  20. * 初始化
  21. */
  22. public void init() throws ServletException
  23. {}
  24. /**
  25. * doGet()方法
  26. */
  27. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  28. {
  29. doPost(request, response);
  30. }
  31. /**
  32. * doPost()方法
  33. */
  34. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  35. try {
  36. int id = Integer.valueOf(request.getParameter("id"));
  37. int bookCount = Integer.valueOf(request.getParameter("bookCount"));
  38. Class.forName("com.mysql.jdbc.Driver");
  39. String url = "jdbc:mysql://localhost:3306/student";
  40. String userName = "roots"; // 用户名
  41. String userPwd = "123456"; // 密码
  42. Connection conn = DriverManager.getConnection(url, userName, userPwd);
  43. String sql = "update tb_books set bookCount=? where id=?";
  44. PreparedStatement ps = conn.prepareStatement(sql);
  45. ps.setInt(1, bookCount);
  46. ps.setInt(2, id);
  47. ps.executeUpdate();
  48. ps.close();
  49. conn.close();
  50. } catch (Exception e) {
  51. // TODO: handle exception
  52. }
  53. }
  54. /**
  55. * 销毁
  56. */
  57. public void destroy()
  58. {
  59. super.destroy();
  60. }
  61. }

web.xml配置

  1. <servlet>
  2. <servlet-name>JdbcUpdateServlet</servlet-name>
  3. <servlet-class>com.book.web3.JdbcUpdateServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>JdbcUpdateServlet</servlet-name>
  7. <url-pattern>/updateServlet.do</url-pattern> <!--根据不同的url来调用不同的servlet来进行处理。 -->
  8. </servlet-mapping>

操作结果:

修改前



修改后



后面的删除就不介绍了,差不多一样的

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

闽ICP备14008679号