• 自定义MVC的使用


    目录

    前言

    一、搭建自定义mvc框架环境

    二、基础增删改

    三、通用增删改

    四、查询删除

    五、新增修改的前端实现


    前言


    一、搭建自定义mvc框架环境

    首先我们将自定义的mvc打成jar包

           

     --------------------------------------------------------------------------------------------------------------------------------

     

    ---------------------------------------------------------------------------------------------------------------------------------

    可以在我的桌面看到jar包了 

     

     创建一个新项目,导入依赖

    在新建的项目中,将分页标签以及相关的助手类导入

    添加配置文件、web.xml配置 

    二、基础增删改

            代码如下:

    1. package com.zhw.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.zhw.entity.Book;
    8. import com.zhw.util.BaseDao;
    9. import com.zhw.util.DBAccess;
    10. import com.zhw.util.PageBean;
    11. import com.zhw.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. // 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(1, book.getBname());
    62. pst.setObject(2, book.getPrice());
    63. pst.setObject(3, book.getBid());
    64. return pst.executeUpdate();
    65. }
    66. }

    测试代码如下:

    1. package com.zhw.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.zhw.entity.Book;
    8. public class BookDaoTest {
    9. private BookDao bd = 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 = bd.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. Book book = new Book(111234321, "1234321" , 1234321);
    31. try {
    32. bd.add(book);
    33. } catch (Exception e) {
    34. // TODO Auto-generated catch block
    35. e.printStackTrace();
    36. }
    37. }
    38. @Test
    39. public void testDel() {
    40. Book book = new Book(111234321, "12343212222" , 1234321);
    41. try {
    42. bd.edit(book);
    43. } catch (Exception e) {
    44. // TODO Auto-generated catch block
    45. e.printStackTrace();
    46. }
    47. }
    48. @Test
    49. public void testEdit() {
    50. fail("Not yet implemented");
    51. }
    52. }

                    查询全部

                   增加

            先查询看一下数据库中是否存在该书籍

    1. @Test
    2. public void testAdd() {
    3. Book book = new Book(111234321, "1234321" , 1234321);
    4. try {
    5. bd.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(111234321, "12343212222" , 1234321);
    4. try {
    5. bd.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(111234321, "12343212222" , 1234321);
    4. try {
    5. bd.del(book);
    6. } catch (Exception e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }
    10. }

    进数据库看是否删除成功

    三、通用增删改

    对比增删改会发现除了SQL语句以及占位符赋值外其他都相同,那么我们可以写一个通用方法,又因为需要赋值的不一样,我们定义一个数组将需要赋值的字段放入数组中。

    1. public int excuteUpdate(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. }
    1. package com.zhw.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.zhw.entity.Book;
    8. import com.zhw.util.BaseDao;
    9. import com.zhw.util.DBAccess;
    10. import com.zhw.util.PageBean;
    11. import com.zhw.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. // 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. public int add(Book book) throws Exception {
    49. String sql = "insert into t_mvc_book values(?,?,?)";
    50. return super.excuteUpdate(sql , book, new String[] {"bid","bname","price"});
    51. }
    52. // 删除
    53. // public int del(Book book) throws Exception {
    54. // Connection con = DBAccess.getConnection();
    55. // String sql = "delete from t_mvc_book where bid = ?";
    56. // PreparedStatement pst = con.prepareStatement(sql);
    57. // pst.setObject(1, book.getBid());
    58. // return pst.executeUpdate();
    59. // }
    60. public int del(Book book) throws Exception {
    61. String sql = "delete from t_mvc_book where bid = ?";
    62. return super.excuteUpdate(sql , book , new String[] {"bid"});
    63. }
    64. // 修改
    65. // public int edit(Book book) throws Exception {
    66. // Connection con = DBAccess.getConnection();
    67. // String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
    68. // PreparedStatement pst = con.prepareStatement(sql);
    69. // pst.setObject(1, book.getBname());
    70. // pst.setObject(2, book.getPrice());
    71. // pst.setObject(3, book.getBid());
    72. // return pst.executeUpdate();
    73. // }
    74. public int edit(Book book) throws Exception {
    75. String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
    76. return super.excuteUpdate(sql , book , new String[] {"bname","price","bid"});
    77. }
    78. }

     测试一下:

       查询全部

                   增加

            先查询看一下数据库中是否存在该书籍

    1. @Test
    2. public void testAdd() {
    3. Book book = new Book(111234321, "1234321" , 1234321);
    4. try {
    5. bd.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(111234321, "12343212222" , 1234321);
    4. try {
    5. bd.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(111234321, "12343212222" , 1234321);
    4. try {
    5. bd.del(book);
    6. } catch (Exception e) {
    7. // TODO Auto-generated catch block
    8. e.printStackTrace();
    9. }
    10. }

    进数据库看是否删除成功

    四、查询删除

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib prefix="z" uri="http://jsp.zhwLouis"%>
    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. <title>Insert title here</title>
    10. <link
    11. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    12. rel="stylesheet">
    13. <script
    14. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    15. <title>书籍列表</title>
    16. <style type="text/css">
    17. .page-item input {
    18. padding: 0;
    19. width: 40px;
    20. height: 100%;
    21. text-align: center;
    22. margin: 0 6px;
    23. }
    24. .page-item input, .page-item b {
    25. line-height: 38px;
    26. float: left;
    27. font-weight: 400;
    28. }
    29. .page-item.go-input {
    30. margin: 0 10px;
    31. }
    32. </style>
    33. </head>
    34. <body>
    35. <form class="form-inline"
    36. action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
    37. <div class="form-group mb-2">
    38. <input type="text" class="form-control-plaintext" name="bname"
    39. placeholder="请输入书籍名称">
    40. </div>
    41. <button type="submit" class="btn btn-primary mb-2">查询</button>
    42. </form>
    43. <table class="table table-striped bg-success">
    44. <thead>
    45. <tr>
    46. <th scope="col">书籍ID</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. </tr>
    58. </c:forEach>
    59. </tbody>
    60. </table>
    61. <z:page PageBean="${pagebean }"></z:page>
    62. </body>
    63. </html>

     

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

    五、新增修改的前端实现

    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. <form action = "${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post" >
    11. bid:<input type="text" name="bid" value="${b.bid }"><br>
    12. bname:<input type="text" name="bname" value="${b.bname }"><br>
    13. price:<input type="text" name="price" value="${b.price }"><br>
    14. <input type="submit">
    15. </form>
    16. </body>
    17. </html>

  • 相关阅读:
    插件_创蓝图文滑动验证码
    利用逆矩阵简化矩阵多项式
    python rb读取文件 base64加密 byte.decode解密,base64解密
    [七夕节]——html炫酷七夕情人节表白动画特效
    模拟退火补完计划
    【CSH 入门基础 8 -- csh 中 set 与 setenv 的区别 】
    数字孪生技术在光网络中的应用与问题
    PC_OS IO方式之DMA传输方式
    深度 | 新兴软件研发范式崛起,云计算全面走向 Serverless 化
    spring 注解练习
  • 原文地址:https://blog.csdn.net/qq_62331938/article/details/125513371