• 自定义MVC增删改查


    目录

    一、将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去

    二、将分页标签相关文件、及相关助手类导入

    三、完成Book实体类及bookdao的编写

    四、完成通用的增删改方法

    五、完成BookAction

    六.xml的配置 

    七、前台代码的编写 


    一、将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去

    Framework包导成jar包

            ​

     搜索框搜索jar

    选中JAR File,然后点击下一步

     

     红色区域选择路径,点击finish

     

     直接点击Ok就可以了

     将相关依赖的jar包导入

    二、将分页标签相关文件、及相关助手类导入

    将博主之前所写的通用分页文章中util工具包和tag标签导入

     

     

    三、完成Book实体类及bookdao的编写

    1. package com.zwc.entity;
    2. public class Book {
    3. private int bid;
    4. private String bname;
    5. private float price;
    6. public int getBid() {
    7. return bid;
    8. }
    9. public void setBid(int bid) {
    10. this.bid = bid;
    11. }
    12. public String getBname() {
    13. return bname;
    14. }
    15. public void setBname(String bname) {
    16. this.bname = bname;
    17. }
    18. public float getPrice() {
    19. return price;
    20. }
    21. public void setPrice(float price) {
    22. this.price = price;
    23. }
    24. public Book() {
    25. // TODO Auto-generated constructor stub
    26. }
    27. public Book(int bid, String bname, float price) {
    28. super();
    29. this.bid = bid;
    30. this.bname = bname;
    31. this.price = price;
    32. }
    33. @Override
    34. public String toString() {
    35. return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    36. }
    37. }

    Bookdao(基础的增删改)

    1. package com.zwc.dao;
    2. import java.sql.Connection;
    3. import java.sql.PreparedStatement;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.zwc.entity.Book;
    8. import com.zwc.util.BaseDao;
    9. import com.zwc.util.DBAccess;
    10. import com.zwc.util.PageBean;
    11. import com.zwc.util.StringUtils;
    12. public class BookDao extends BaseDao<Book>{
    13. // 查询
    14. public List<Book> list(Book book,PageBean pageBean) throws Exception{
    15. String sql = "select * from t_mvc_book where 1=1 ";
    16. String bname = book.getBname();
    17. if(StringUtils.isNotBlank(bname)) {
    18. sql +=" and bname like '%"+bname+"%'";
    19. }
    20. int bid = book.getBid();
    21. // 前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
    22. if(bid!=0) {
    23. sql +=" and bid ="+bid;
    24. }
    25. return super.executeQuery(sql, pageBean, rs ->{
    26. List<Book> list = new ArrayList<>();
    27. try {
    28. while(rs.next()) {
    29. list.add(new Book(rs.getInt("bid"), rs.getString("bname"),rs.getFloat("price")));
    30. }
    31. } catch (SQLException e) {
    32. e.printStackTrace();
    33. }
    34. return list;
    35. });
    36. }
    37. // 增
    38. public int add(Book book) throws Exception {
    39. Connection con = DBAccess.getConnection();
    40. String sql="insert into t_mvc_book values(?,?,?)";
    41. PreparedStatement pst = con.prepareStatement(sql);
    42. pst.setObject(1, book.getBid());
    43. pst.setObject(2, book.getBname());
    44. pst.setObject(3, book.getPrice());
    45. return pst.executeUpdate();
    46. }
    47. // 删
    48. public int del(Book book) throws Exception {
    49. Connection con = DBAccess.getConnection();
    50. String sql="delete from t_mvc_book where bid = ?";
    51. PreparedStatement pst = con.prepareStatement(sql);
    52. pst.setObject(1, book.getBid());
    53. return pst.executeUpdate();
    54. }
    55. // 改
    56. public int edit(Book book) throws Exception {
    57. Connection con = DBAccess.getConnection();
    58. String sql="update t_mvc_book set bname=?,price=? where bid = ?";
    59. PreparedStatement pst = con.prepareStatement(sql);
    60. pst.setObject(1, book.getBname());
    61. pst.setObject(2, book.getPrice());
    62. pst.setObject(3, book.getBid());
    63. return pst.executeUpdate();
    64. }
    65. }

    四、完成通用的增删改方法

    大家可以发现上面基础的增删改代码都有一些相同代码


            Connection con = DBAccess.getConnection();
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setObject(1, book.getBname());
            pst.setObject(2, book.getPrice());

            pst.setObject(3, book.getBid());
     

    所以我们要把它写成一个通用增删改

    因为我们bookdao继承了basedao

    basedao:

    1. package com.zwc.util;
    2. import java.lang.reflect.Field;
    3. import java.sql.Connection;
    4. import java.sql.PreparedStatement;
    5. import java.sql.ResultSet;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. import com.zwc.entity.Book;
    9. /**
    10. * T代表实体类,可以是book/User/Goods...
    11. * @author Administrator
    12. *
    13. * @param <T>
    14. */
    15. public class BaseDao<T> {
    16. // public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
    17. sql="select * from t_mvc_book WHERE bname like '%圣墟%'";
    18. 从上面得到select COUNT(1) as n from (select * from t_mvc_book WHERE bname like '%圣墟%') t;
    19. 目的是为了得到总记录数->得到总页数
    20. // select * from t_mvc_book WHERE bname like '%圣墟%' LIMIT 10,10;
    21. //
    22. // /**
    23. // * 1、拿到数据库连接
    24. // * 2、拿到preparestatement
    25. // * 3、执行sql语句
    26. // */
    27. // Connection con = DBAccess.getConnection();//重复代码1
    28. // PreparedStatement pst = con.prepareStatement(sql);//重复代码2
    29. // ResultSet rs = pst.executeQuery();//重复代码3
    30. while(rs.next()) {
    31. list.add(new Book(rs.getInt("bid"), rs.getString("bname"),rs.getFloat("price") ));
    32. }
    33. 查询不同表,必然要处理不同的结果集
    34. 接口是调用方来实现
    35. // return callBack.foreach(rs);
    36. // }
    37. public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
    38. /**
    39. * 1、拿到数据库连接
    40. * 2、拿到preparestatement
    41. * 3、执行sql语句
    42. */
    43. Connection con = null;//重复代码1
    44. PreparedStatement pst = null;//重复代码2
    45. ResultSet rs = null;//重复代码3
    46. if(pageBean !=null && pageBean.isPagination()) {
    47. String countSQL = getCountSQL(sql);
    48. con = DBAccess.getConnection();
    49. pst = con.prepareStatement(countSQL);
    50. rs = pst.executeQuery();
    51. if(rs.next()) {
    52. // 当前实体类就包含了记录数
    53. pageBean.setTotal(rs.getString("n"));
    54. }
    55. String pageSQL = getPageSQL(sql,pageBean);
    56. con = DBAccess.getConnection();
    57. pst = con.prepareStatement(pageSQL);
    58. rs = pst.executeQuery();
    59. }
    60. else {
    61. con = DBAccess.getConnection();
    62. pst = con.prepareStatement(sql);
    63. rs = pst.executeQuery();
    64. }
    65. // 查询不同表,必然要处理不同的结果集
    66. // 接口是调用方来实现
    67. return callBack.foreach(rs);
    68. }
    69. /**
    70. * 拼装第n页的数据的sql
    71. * @param sql
    72. * @param pageBean
    73. * @return
    74. */
    75. private String getPageSQL(String sql, PageBean pageBean) {
    76. return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows();
    77. }
    78. /**
    79. * 拼装符合条件总记录数的sql
    80. * @param sql
    81. * @return
    82. */
    83. private String getCountSQL(String sql) {
    84. // sql="select * from t_mvc_book WHERE bname like '%圣墟%'";
    85. // 从上面得到select COUNT(1) as n from (select * from t_mvc_book WHERE bname like '%圣墟%') t;
    86. return "select count(1) as n from ("+sql+") t";
    87. }
    88. public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
    89. Connection con = DBAccess.getConnection();
    90. PreparedStatement pst = con.prepareStatement(sql);
    91. // 将t的某一个属性对应的值加到pst对象中
    92. for (int i = 0; i < attrs.length; i++) {
    93. Field f = t.getClass().getDeclaredField(attrs[i]);
    94. f.setAccessible(true);
    95. pst.setObject(i+1, f.get(t));
    96. }
    97. return pst.executeUpdate();
    98. }
    99. }

    Bookdao :

    1. package com.zwc.dao;
    2. import java.sql.Connection;
    3. import java.sql.PreparedStatement;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.zwc.entity.Book;
    8. import com.zwc.util.BaseDao;
    9. import com.zwc.util.DBAccess;
    10. import com.zwc.util.PageBean;
    11. import com.zwc.util.StringUtils;
    12. public class BookDao extends BaseDao<Book>{
    13. // 查询
    14. public List<Book> list(Book book,PageBean pageBean) throws Exception{
    15. String sql = "select * from t_mvc_book where 1=1 ";
    16. String bname = book.getBname();
    17. if(StringUtils.isNotBlank(bname)) {
    18. sql +=" and bname like '%"+bname+"%'";
    19. }
    20. int bid = book.getBid();
    21. // 前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
    22. if(bid!=0) {
    23. sql +=" and bid ="+bid;
    24. }
    25. return super.executeQuery(sql, pageBean, rs ->{
    26. List<Book> list = new ArrayList<>();
    27. try {
    28. while(rs.next()) {
    29. list.add(new Book(rs.getInt("bid"), rs.getString("bname"),rs.getFloat("price")));
    30. }
    31. } catch (SQLException e) {
    32. e.printStackTrace();
    33. }
    34. return list;
    35. });
    36. }
    37. // 增
    38. public int add(Book book) throws Exception {
    39. String sql="insert into t_mvc_book values(?,?,?)";
    40. // super调用basedao最后一个方法
    41. return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
    42. }
    43. // 删
    44. public int del(Book book) throws Exception {
    45. String sql="delete from t_mvc_book where bid = ?";
    46. return super.executeUpdate(sql, book,new String[] {"bid"});
    47. }
    48. // 改
    49. public int edit(Book book) throws Exception {
    50. String sql="update t_mvc_book set bname=?,price=? where bid = ?";
    51. return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
    52. }
    53. }

    五、完成BookAction

            BookAction:

    1. package com.zwc.web;
    2. import java.util.List;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import com.zwc.dao.BookDao;
    6. import com.zwc.entity.Book;
    7. import com.zwc.framework.ActionSupport;
    8. import com.zwc.framework.ModelDrivetr;
    9. import com.zwc.util.PageBean;
    10. public class BookAction extends ActionSupport implements ModelDrivetr<Book>{
    11. private Book b = new Book();
    12. private BookDao book = new BookDao();
    13. @Override
    14. public Book getModel() {
    15. return b;
    16. }
    17. // 增
    18. public String add(HttpServletRequest req, HttpServletResponse resp) {
    19. try {
    20. book.add(b);
    21. } catch (Exception e) {
    22. e.printStackTrace();
    23. }
    24. // tolist代表跳到查询方法
    25. return "toList";
    26. }
    27. // 删
    28. public String del(HttpServletRequest req, HttpServletResponse resp) {
    29. try {
    30. book.del(b);
    31. } catch (Exception e) {
    32. e.printStackTrace();
    33. }
    34. // tolist代表跳到查询方法
    35. return "toList";
    36. }
    37. // 修改
    38. public String edit(HttpServletRequest req, HttpServletResponse resp) {
    39. try {
    40. book.edit(b);
    41. } catch (Exception e) {
    42. e.printStackTrace();
    43. }
    44. // tolist代表跳到查询方法
    45. return "toList";
    46. }
    47. // 查询
    48. public String list(HttpServletRequest req, HttpServletResponse resp) {
    49. try {
    50. PageBean pageBean = new PageBean();
    51. pageBean.setRequest(req);
    52. List<Book> list = book.list(b, pageBean);
    53. req.setAttribute("list", list);
    54. req.setAttribute("pageBean", pageBean);
    55. } catch (Exception e) {
    56. e.printStackTrace();
    57. }
    58. // 执行查询展示
    59. return "list";
    60. }
    61. // 跳转到新增/修改界面
    62. public String preEdit(HttpServletRequest req, HttpServletResponse resp) {
    63. try {
    64. int bid = b.getBid();
    65. if(bid!=0) {
    66. // 传递bid到后台,有且只能查出一条数据,那也就意味着list集合中只有一条
    67. List<Book> list = book.list(b, null);
    68. req.setAttribute("b", list.get(0));
    69. }
    70. } catch (Exception e) {
    71. e.printStackTrace();
    72. }
    73. // tolist代表跳到编辑方法
    74. return "toEdit";
    75. }
    76. }

    六.xml的配置 

    web.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    3. <display-name>T280_recf</display-name>
    4. <servlet>
    5. <servlet-name>mvc</servlet-name>
    6. <servlet-class>com.zwc.framework.DispatcherServlet</servlet-class>
    7. <init-param>
    8. <param-name>configLocation</param-name>
    9. <param-value>/zwc.xml</param-value>
    10. </init-param>
    11. </servlet>
    12. <servlet-mapping>
    13. <servlet-name>mvc</servlet-name>
    14. <url-pattern>*.action</url-pattern>
    15. </servlet-mapping>
    16. </web-app>

    XML配置 

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.zwc.web.BookAction">
    4. <forward name="list" path="/bookList.jsp" redirect="false" />
    5. <forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
    6. <forward name="toList" path="/book.action?methodName=list" redirect="true" />
    7. </action>
    8. </config>

    七、前台代码的编写 

    主界面

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib prefix="z" uri="http://jsp.zwcedu.cn" %>
    4. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    6. <html>
    7. <head>
    8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    9. <link
    10. href='https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css'
    11. rel='stylesheet'>
    12. <script
    13. src='https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js'></script>
    14. <title>书籍列表</title>
    15. <style type="text/css">
    16. .page-item input {
    17. padding: 0;
    18. width: 40px;
    19. height: 100%;
    20. text-align: center;
    21. margin: 0 6px;
    22. }
    23. .page-item input, .page-item b {
    24. line-height: 38px;
    25. float: left;
    26. font-weight: 400;
    27. }
    28. .page-item.go-input {
    29. margin: 0 10px;
    30. }
    31. </style>
    32. </head>
    33. <body>
    34. <form class="form-inline"
    35. action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="bname"
    38. placeholder="请输入书籍名称">
    39. </div>
    40. <button type="submit" class="btn btn-primary mb-2">查询</button>
    41. </form>
    42. <table class="table table-striped ">
    43. <thead>
    44. <tr>
    45. <th scope="col">书籍ID</th>
    46. <th scope="col">书籍名</th>
    47. <th scope="col">价格</th>
    48. <th scope="col">操作</th>
    49. </tr>
    50. </thead>
    51. <tbody>
    52. <c:forEach items="${list}" var="b">
    53. <tr>
    54. <td>${b.bid}</td>
    55. <td>${b.bname}</td>
    56. <td>${b.price}</td>
    57. <td>
    58. <a href="${pageContext.request.contextPath }/book.action?methodName=preEdit&bid=${b.bid}">编辑</a>
    59. <a href="${pageContext.request.contextPath }/book.action?methodName=del&bid=${b.bid}">删除</a>
    60. <a href="${pageContext.request.contextPath }/book.action?methodName=preEdit">新增</a>
    61. </td>
    62. </tr>
    63. </c:forEach>
    64. </tbody>
    65. </table>
    66. <z:page pageBean="${pageBean }"></z:page>
    67. </body>
    68. </html>

    编辑界面

    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. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. <center>
    11. <form action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
    12. 编号:<input type="text" name="bid" value="${b.bid }"><br>
    13. 名字:<input type="text" name="bname" value="${b.bname }"><br>
    14. 价格:<input type="text" name="price" value="${b.price}">
    15. <input type="submit" value="提交">
    16. </form>
    17. </center>
    18. </body>
    19. </html>

    主界面效果图:

     

    点击编辑进入编辑界面,点击提交

     

     在主界面可以看到已经改了

    点击增加到增加页面点击提交

     

    主界面展示

     

     点击删除,编号为28的数据

     


     主界面没有编号为28的数据了 

  • 相关阅读:
    关于癌细胞MR的几种类型,T1,T2,DCE,DWI,ADC
    [激光原理与应用-19]:《激光原理与技术》-5- 激光器的增益、损耗、自激振荡条件
    现代cpp教程笔记
    sas小笔记-字符函数/时间函数
    如何将PCB区域修改为板子形状大小(修改黑色区域大小)
    数据结构— —循环队列
    凯利公式 - Kelly formula
    (图论) 1020. 飞地的数量 ——【Leetcode每日一题】
    QT----写完的程序打包为APK在自己的手机上运行
    [ruby on rails]rack-cors, rack-attack
  • 原文地址:https://blog.csdn.net/qq_65345936/article/details/125517196