• 自定义MVC增删改查


     


    目录

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

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

    3.框架的配置文件添加、以及web.xml的配置-以后开源框架的使用从这一步开始

    4.完成Book实体类及bookDao的编写

    5.完成通用的增删改方法

    6.完成BookAction

    7.完成mvc.xml的配置

    8.完成前台代码的编写

    9.总结


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

                            

                     

                     

        

                     

      

                                    

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

     3.框架的配置文件添加、以及web.xml的配置-以后开源框架的使用从这一步开始

                                            

                                             

    4.完成Book实体类及bookDao的编

    1. package com.ycx.entity;
    2. public class Book {
    3. private int bid;
    4. private String bname;
    5. private float price;
    6. public Book() {
    7. // TODO Auto-generated constructor stub
    8. }
    9. public int getBid() {
    10. return bid;
    11. }
    12. public void setBid(int bid) {
    13. this.bid = bid;
    14. }
    15. public String getBname() {
    16. return bname;
    17. }
    18. public void setBname(String bname) {
    19. this.bname = bname;
    20. }
    21. public float getPrice() {
    22. return price;
    23. }
    24. public void setPrice(float price) {
    25. this.price = price;
    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. }
    1. package com.ycx.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.ycx.entity.Book;
    8. import com.ycx.util.BaseDao;
    9. import com.ycx.util.DBAccess;
    10. import com.ycx.util.PageBean;
    11. import com.ycx.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 (Exception e) {
    32. // TODO Auto-generated catch block
    33. e.printStackTrace();
    34. }
    35. return list;
    36. });
    37. }
    38. // 增
    39. public int add(Book book) throws Exception {
    40. Connection con = DBAccess.getConnection();
    41. String sql="insert into t_mvc_book values (?,?,?)";
    42. PreparedStatement pst = con.prepareStatement(sql);
    43. pst.setObject(1, book.getBid());
    44. pst.setObject(2, book.getBname());
    45. pst.setObject(3, book.getPrice());
    46. return pst.executeUpdate();
    47. }
    48. // 删
    49. public int del(Book book) throws Exception {
    50. Connection con = DBAccess.getConnection();
    51. String sql="delete from t_mvc_book where bid= ?";
    52. PreparedStatement pst = con.prepareStatement(sql);
    53. pst.setObject(1, book.getBid());
    54. return pst.executeUpdate();
    55. }
    56. // 改
    57. public int edit(Book book) throws Exception {
    58. Connection con = DBAccess.getConnection();
    59. String sql="update t_mvc_book set bname=?,price=?, where bid=?";
    60. PreparedStatement pst = con.prepareStatement(sql);
    61. pst.setObject(3, book.getBid());
    62. pst.setObject(1, book.getBname());
    63. pst.setObject(2, book.getPrice());
    64. return pst.executeUpdate();
    65. }
    66. }

    然后用junit4去测试:

    ctrl+n

     

     

     之后就自动生成了一个BookDaoTest:

    1. package com.ycx.dao;
    2. import static org.junit.Assert.*;
    3. import java.util.List;
    4. import org.junit.After;
    5. import org.junit.Before;
    6. import org.junit.Test;
    7. import com.ycx.entity.Book;
    8. public class BookDaoTest {
    9. private BookDao bookDao=new BookDao();
    10. @Before
    11. public void setUp() throws Exception {
    12. }
    13. @After
    14. public void tearDown() throws Exception {
    15. }
    16. @Test
    17. public void testList() {
    18. try {
    19. List<Book> list = bookDao.list(new Book(), null);
    20. for (Book book : list) {
    21. System.out.println(book);
    22. }
    23. } catch (Exception e) {
    24. // TODO Auto-generated catch block
    25. e.printStackTrace();
    26. }
    27. }
    28. @Test
    29. public void testAdd() {
    30. fail("Not yet implemented");
    31. }
    32. @Test
    33. public void testDel() {
    34. fail("Not yet implemented");
    35. }
    36. @Test
    37. public void testEdit() {
    38. fail("Not yet implemented");
    39. }
    40. }

    测试查询所有:

    打印结果如下

     

     测试分页查询:

    1. @Test
    2. public void testList() {
    3. try {
    4. List<Book> list = bookDao.list(new Book(), new PageBean());
    5. for (Book book : list) {
    6. System.out.println(book);
    7. }
    8. } catch (Exception e) {
    9. // TODO Auto-generated catch block
    10. e.printStackTrace();
    11. }
    12. }

    结果如下:

     测试新增数据:

    1. @Test
    2. public void testAdd() {
    3. Book book = new Book(1234321, "1234321", 1234321);
    4. try {
    5. bookDao.add(book);
    6. } catch (Exception e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }
    10. }

    结果如下:

     测试修改:

    1. @Test
    2. public void testEdit() {
    3. Book book = new Book(1234321, "123432100", 1234321);
    4. try {
    5. bookDao.edit(book);
    6. } catch (Exception e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }
    10. }

    结果如下:

     测试删除:

    1. @Test
    2. public void testDel() {
    3. Book book = new Book(1234321, "1234321", 1234321);
    4. try {
    5. bookDao.del(book);
    6. } catch (Exception e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }
    10. }

    5.完成通用的增删改方法

    BaseDao:

    1. public int executeUpdate(String sql,T t,String [] attrs) throws Exception {
    2. Connection con = DBAccess.getConnection();
    3. PreparedStatement pst = con.prepareStatement(sql);
    4. // 将T的某一个属性对应的值加到 pst 对象中
    5. for (int i = 0; i < attrs.length; i++) {
    6. Field f = t.getClass().getDeclaredField(attrs[i]);
    7. f.setAccessible(true);
    8. pst.setObject(i+1, f.get(t));
    9. }
    10. return pst.executeUpdate();
    11. }

    BookDao:

    1. package com.ycx.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.ycx.entity.Book;
    8. import com.ycx.util.BaseDao;
    9. import com.ycx.util.DBAccess;
    10. import com.ycx.util.PageBean;
    11. import com.ycx.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 (Exception e) {
    32. // TODO Auto-generated catch block
    33. e.printStackTrace();
    34. }
    35. return list;
    36. });
    37. }
    38. // 增
    39. public int add(Book book) throws Exception {
    40. String sql="insert into t_mvc_book values (?,?,?)";
    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. }

    6.完成BookAction

    1. package com.ycx.web;
    2. import java.util.List;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import com.ycx.dao.BookDao;
    6. import com.ycx.entity.Book;
    7. import com.ycx.framework.ActionSupport;
    8. import com.ycx.framework.ModelDriven;
    9. import com.ycx.util.PageBean;
    10. public class BookAction extends ActionSupport implements ModelDriven<Book>{
    11. private Book book=new Book();
    12. private BookDao bookDao=new BookDao();
    13. @Override
    14. public Book getModel() {
    15. return null;
    16. }
    17. // 增
    18. public String add(HttpServletRequest req, HttpServletResponse resp) {
    19. try {
    20. bookDao.add(book);
    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. bookDao.del(book);
    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. bookDao.edit(book);
    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 = bookDao.list(book, 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 = book.getBid();
    65. if(bid != 0) {
    66. // 传递bid到后台,有且只能查出一条数据,那也就意味着list集合中只有一条
    67. List<Book> list = bookDao.list(book, null);
    68. req.setAttribute("b", list.get(0));
    69. }
    70. } catch (Exception e) {
    71. e.printStackTrace();
    72. }
    73. // 代表跳到编辑界面
    74. return "toEdit";
    75. }
    76. }

    7.完成mvc.xml的配置

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

    8.完成前台代码的编写

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@taglib uri="http://ycx.com" prefix="y" %>
    4. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    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. </tr>
    49. </thead>
    50. <tbody>
    51. <c:forEach items="${list }" var="b">
    52. <tr>
    53. <td>${b.bid }</td>
    54. <td>${b.bname }</td>
    55. <td>${b.price }</td>
    56. </tr>
    57. </c:forEach>
    58. </tbody>
    59. </table>
    60. <y:page pageBean="${pageBean }"></y:page>
    61. </body>
    62. </html>

     

     

    9.总结

    自定义MVC框架应用中最为关键的是要把自定义MVC框架打造好,其中在应用是也要注意细节,比如:改造.xml文件时要跳转的目的类。

  • 相关阅读:
    JavaEE多线程知识--计时器
    利用PaddleDetection 训练自定义VOC数据集进行目标检测
    Java 简单易懂的JSON框架
    【iOS】——SDWebImage源码学习
    后端使用aop和redis实现防抖
    Day42 尚硅谷JUC——Fork_Join分支合并框架
    Vue中...(扩展运算符)的作用
    海水稻种植面积超100万亩 国稻种芯-何登骥:四大类典型覆盖
    人群聚集逻辑
    mysql高阶语句
  • 原文地址:https://blog.csdn.net/weixin_65808248/article/details/125513427