前言
在前面两期博客中我们了解了关于自定义MVC框架对之前代码的一些优化原理,今天我给大家带来的是自定义MVC框架的综合运用(增删改查),
下面由我来给大家分享(跟着我们的思维导图一起了解一下)
所需文件
链接:https://pan.baidu.com/s/1vHTem1HD1CEdjGTmJuPAFQ
提取码:yx04
该链接将本次分享所需的文件包含在内了,有需要课前往下载
1.将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
1.1将框架打成jar包
如图所示
1.2 导入所需的jar包
2.将分页标签相关文件、及相关助手类导入
2.1导入数据工具类文件
(由于代码过多,如图所示)
2.2 导入分页工具类
3. 项目环境搭建
3.1 框架的配置文件添加
右击scr新建一个Source Folder文件夹,在此文件夹中新建一个.xml文件
(如图所示)
mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?> <config> <!-- 在这里每加一个配置,就相当于actions.put("/goods", new GoodsAction()); 这样就解决了代码灵活性的问题 --> <action path="/book" type="com.YX.Web.BookAction"> <!-- 查询:BookList.jsp 返回值:list --> <!-- * 增删改确定:book.action?methodName=list 返回值:toList --> <!-- * 增加修改跳转对应界面:bookEdit.jsp 返回值:toEdit --> <forward name="list" path="/bookList.jsp" redirect="false" /> <forward name="toList" path="/book.action?methodName=list" redirect="true" /> <forward name="toEdit" path="/bookEdit.jsp" redirect="false" /> </action> </config>
3.2 web.xml的配置
web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <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"> <display-name>YX_MVC_project</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>com.zking.framework.DispatchServlet</servlet-class> <init-param> <param-name>configurationLocation</param-name> <param-value>/mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
4. 实体类和Dao方法类的编写
实体类Book类
package com.YX.entity; /**实体类:书籍类 * @author 君易--鑨 * 2023年7月3日下午10:00:37 * */ public class Book { //定义属性 private int bid; private String bname; private float price; // 获取属性对应的get和set方法 public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } /** * 无参构造 */ public Book() { // TODO Auto-generated constructor stub } /** * 有参构造 * @param bid * @param bname * @param price */ public Book(int bid, String bname, float price) { super(); this.bid = bid; this.bname = bname; this.price = price; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } }
Dao方法类BookDao类
package com.YX.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.YX.entity.Book; import com.YX.until.BaseDao; import com.YX.until.DBAccess; import com.YX.until.PageBean; import com.YX.until.StringUtils; /** * 数据库方法类 * * @author 君易--鑨 2023年7月3日下午10:04:40 * */ public class BookDao extends BaseDao<Book> { /** * 查询的方法 * * @param book * 带有查询内容的实体对象 * @param pageBean * 分页工具类 * @return * @throws Exception */ public List<Book> list(Book book, PageBean pageBean) throws Exception { String sql = "select * from t_mvc_book where 1=1 "; // 获取查询的书名 String bname = book.getBname(); // 获取书籍id int bid = book.getBid(); if (StringUtils.isNotBlank(bname)) {// 判断查询的书名不为空 sql += " and bname like '%" + bname + "%'"; } if (bid != 0) {// 判断id不等于0,说明传了id过来 sql += " and bid = " + bid; } return super.executeQuery(sql, Book.class, pageBean); } /** * 新增的方法 * * @param book * 新增的实体对象 * @return * @throws Exception */ public int add(Book book) throws Exception { // 编写sql语句 String sql = "insert into t_mvc_book values (?,?,?)"; return super.executeUpdate(sql, book, new String[] { "bid", "bname", "price" }); } /** * 删除的方法 * * @param book * 指定信息 * @return * @throws Exception */ public int del(Book book) throws Exception { // 编写sql语句 String sql = "delete from t_mvc_book where bid = ?"; return super.executeUpdate(sql, book, new String[] { "bid" }); } public int edit(Book book) throws Exception { // 编写sql语句 String sql = "update t_mvc_book set bname = ?,price = ? where bid = ?"; return super.executeUpdate(sql, book, new String[] { "bname", "price", "bid" }); } }
Dao方法的Junit测试类(BookDaoTest)
package com.YX.Dao; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import com.YX.entity.Book; import com.YX.until.PageBean; /**junit测试类用于测试方法 * @author 君易--鑨 * 2023年7月3日下午10:35:14 * */ public class BookDaoTest { // 实例化Dao方法 private BookDao bookdao=new BookDao(); @Test public void testList() { // 实例化实体对象 Book book =new Book(); book.setBname("君易");//设置查询的内容 PageBean pageBean=new PageBean(); // pageBean.setPage();//设置查询第几页 pageBean.setPagination(false);//设置分页 try { List<Book> list = bookdao.list(book, pageBean); for (Book b : list) { System.out.println(b); } } catch (Exception e) { e.printStackTrace(); } } @Test public void testAdd() { // 实例化实体对象 Book book =new Book(); // 设置要新增的书籍 book.setBid(52); book.setBname("君易--鑨"); book.setPrice(52); // 调用方法 try { bookdao.add(book); } catch (Exception e) { e.printStackTrace(); } } @Test public void testDel() { // 实例化实体对象 Book book =new Book(); // 设置要删除的书籍 book.setBid(52); // 调用方法 try { bookdao.del(book); } catch (Exception e) { e.printStackTrace(); } } @Test public void testEdit() { // 实例化实体对象 Book book =new Book(50,"君易--鑨",520); // 调用方法 try { bookdao.edit(book); } catch (Exception e) { e.printStackTrace(); } } }
查看测试结果(带模糊查询和分页)
删除后查询测试结果
修改后查询结果
新增后查询结果
5. 完成BookAction类的代码
package com.YX.Web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.YX.Dao.BookDao; import com.YX.entity.Book; import com.YX.until.PageBean; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; /** * * @author 君易--鑨 2023年7月3日下午11:38:40 * */ public class BookAction extends ActionSupport implements ModelDriver<Book> { private Book book = new Book();// 实例化实体对象 private BookDao bookdao = new BookDao();// 实例化dao方法 // 查询 bookList.jsp public String list(HttpServletRequest req, HttpServletResponse resp) { PageBean pageBean = new PageBean();// 实例化分页工具类 pageBean.setRequest(req);// 初始化分页工具 try { List<Book> lst = bookdao.list(book, pageBean);// 调用方法 // 存储起来回显到界面上 req.setAttribute("lst", lst); req.setAttribute("pageBean", pageBean); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "list"; } // 编辑页面跳转 bookEdit.jsp public String toEdit(HttpServletRequest req, HttpServletResponse resp) { try { if (book.getBid() != 0) { List<Book> lst = bookdao.list(book, null);// 调用方法 // 存储起来回显到界面上 req.setAttribute("b", lst.get(0)); } } catch (Exception e) { e.printStackTrace(); } return "toEdit"; } // 增加 public String add(HttpServletRequest req, HttpServletResponse resp) { try { bookdao.add(book);// 调用方法 } catch (Exception e) { e.printStackTrace(); } return "toList"; } // 删除 public String del(HttpServletRequest req, HttpServletResponse resp) { try { bookdao.del(book);// 调用方法 } catch (Exception e) { e.printStackTrace(); } return "toList"; } // 修改 public String edit(HttpServletRequest req, HttpServletResponse resp) { try { bookdao.edit(book);// 调用方法 } catch (Exception e) { e.printStackTrace(); } return "toList"; } @Override public Book getModel() { // TODO Auto-generated method stub return book; } }
6. 前端代码
bookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/YX" prefix="yx"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script> <title>书籍列表</title> <style type="text/css"> .page-item input { padding: 0; width: 40px; height: 100%; text-align: center; margin: 0 6px; } .page-item input, .page-item b { line-height: 38px; float: left; font-weight: 400; } .page-item.go-input { margin: 0 10px; } </style> </head> <body> <form class="form-inline" action="${pageContext.request.contextPath }/book.action?methodName=list" method="post"> <div class="form-group mb-2"> <input type="text" class="form-control-plaintext" name="bname" placeholder="请输入书籍名称"> <!-- <input name="rows" value="20" type="hidden"> --> <!-- 不想分页 --> <input name="pagination" value="false" type="hidden"> </div> <button type="submit" class="btn btn-primary mb-2">查询</button> <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增</a> </form> <table class="table table-striped bg-success"> <thead> <tr> <th scope="col">书籍ID</th> <th scope="col">书籍名</th> <th scope="col">价格</th> <th scope="col">操作</th> </tr> </thead> <tbody> <c:forEach var="b" items="${lst }"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> <td> <a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a> <a href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a> </td> </tr> </c:forEach> </tbody> </table> <!-- 这一行代码就相当于前面分页需求前端的几十行了 --> <yx:page pageBean="${pageBean }"></yx:page> </body> </html>
bookEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/YX" prefix="yx"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script> <title>书籍列表</title> <style type="text/css"> .page-item input { padding: 0; width: 40px; height: 100%; text-align: center; margin: 0 6px; } .page-item input, .page-item b { line-height: 38px; float: left; font-weight: 400; } .page-item.go-input { margin: 0 10px; } </style> </head> <body> <form class="form-inline" action="${pageContext.request.contextPath }/book.action?methodName=list" method="post"> <div class="form-group mb-2"> <input type="text" class="form-control-plaintext" name="bname" placeholder="请输入书籍名称"> <!-- <input name="rows" value="20" type="hidden"> --> <!-- 不想分页 --> <input name="pagination" value="false" type="hidden"> </div> <button type="submit" class="btn btn-primary mb-2">查询</button> <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增</a> </form> <table class="table table-striped bg-success"> <thead> <tr> <th scope="col">书籍ID</th> <th scope="col">书籍名</th> <th scope="col">价格</th> <th scope="col">操作</th> </tr> </thead> <tbody> <c:forEach var="b" items="${lst }"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> <td> <a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a> <a href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a> </td> </tr> </c:forEach> </tbody> </table> <!-- 这一行代码就相当于前面分页需求前端的几十行了 --> <yx:page pageBean="${pageBean }"></yx:page> </body> </html>
页面展示
结束语
这期博客给大家分享到这,希望大家能点击关注,后续会继续分享知识。