前言:我们通过框架的形式实现一个具有增删改查的网页。
一.将MVC框架源码导成jar包
1.1优化的思路:
相比我们上篇所讲的MVC框架,我们今天所要优化的代码是要更加的方便,我们只要将之前的代码封装成一个jar形式的实现一个增删改查的操作。
1.2具体步骤:
打开eclipse,创建项目后
选择存放的位置
出现这个就导成功了!!!
二.创建需要的工具包
分析思路:
我们所要使用的工具包有:entity(实体类),Dao(存放具体的方法),util(存放工具类),tag(标签助手类),web(控制器类),conf(存放配置文件)
2.1具体的代码:
entity
package com.lya.entity; /** * 实体类 * * @author 李永安 * * @date:2023年7月3日 下午5:01:23 * */ public class Book { private int bid; private String bname; private float price; /** * */ public Book() { // TODO Auto-generated constructor stub } 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(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.lya.Dao; import java.util.List; import com.lya.entity.Book; import com.lya.util.BaseDao; import com.lya.util.PageBean; /** * 书籍的方法类 * * @author 李永安 * * @date:2023年7月3日 下午5:03:46 * */ public class BookDao extends BaseDao<Book> { /** * 附带id,name的查询 * * @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(); if (bname !=null) { sql += " and bname like " + bname; } int bid = book.getBid(); if (bid != 0) { sql += " and bid =" + bid; } return super.executeQuery(sql, Book.class, pagebean); } public static void main(String[] args) throws Exception { System.out.println(new BookDao().list(new Book(), null)); } /** * 增加 * * @return * @throws Exception */ public int add(Book book) throws Exception { String sql = "insert into t_mvc_book values(?,?,?)"; return super.executeUpdate(sql, book, new String[] { "bid", "bname", "price" }); } /** * 删除 * * @return * @throws Exception */ public int del(Book book) throws Exception { String sql = "delete from t_mvc_book where did= " + book.getBid(); return super.executeUpdate(sql, book, new String[] {"bid"}); } /** * 修改 * * @return * @throws Exception */ public int edit(Book book) throws Exception { String sql = "update t_mvc_book set bname = ?, price = ? where bid = "+book.getBid(); return super.executeUpdate(sql, book, new String[] { "bname", "price", "bid" }); } }
通过JUnit运行测试Dao类的方法
之后我们继续写
util类
basedao:
package com.lya.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * 所有Dao层的父类 * BookDao * UserDao * OrderDao * ... * @author Administrator * * @param <T> */ public class BaseDao<T> { /** * 通用的增删改方法 * @param book * @throws Exception */ public int executeUpdate(String sql, T t, String[] attrs) throws Exception { // String[] attrs = new String[] {"bid", "bname", "price"}; Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); for (int i = 0; i < attrs.length; i++) { Field f = t.getClass().getDeclaredField(attrs[i]); f.setAccessible(true); pst.setObject(i+1, f.get(t)); } return pst.executeUpdate(); } /** * 通用分页查询 * @param sql * @param clz * @return * @throws Exception */ public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{ List<T> list = new ArrayList<T>(); Connection con = DBAccess.getConnection();; PreparedStatement pst = null; ResultSet rs = null; /* * 是否需要分页? * 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) * 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...) */ if(pageBean != null && pageBean.isPagination()) { // 必须分页(列表需求) String countSQL = getCountSQL(sql); pst = con.prepareStatement(countSQL); rs = pst.executeQuery(); if(rs.next()) { pageBean.setTotal(String.valueOf(rs.getObject(1))); } // 挪动到下面,是因为最后才处理返回的结果集 // -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%' // -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据 // -- countSql=select count(1) from (sql) t 符合条件的总记录数 String pageSQL = getPageSQL(sql,pageBean);//符合条件的某一页数据 pst = con.prepareStatement(pageSQL); rs = pst.executeQuery(); }else { // 不分页(select需求) pst = con.prepareStatement(sql);//符合条件的所有数据 rs = pst.executeQuery(); } while (rs.next()) { T t = clz.newInstance(); Field[] fields = clz.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); f.set(t, rs.getObject(f.getName())); } list.add(t); } return list; } /** * 将原生SQL转换成符合条件的总记录数countSQL * @param sql * @return */ private String getCountSQL(String sql) { // -- countSql=select count(1) from (sql) t 符合条件的总记录数 return "select count(1) from ("+sql+") t"; } /** * 将原生SQL转换成pageSQL * @param sql * @param pageBean * @return */ private String getPageSQL(String sql,PageBean pageBean) { // (this.page - 1) * this.rows // pageSql=sql limit (page-1)*rows,rows return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows(); } }
tag
pagetag:
package com.lya.tag; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.lya.util.PageBean; public class PageTag extends BodyTagSupport{ private PageBean pageBean;// 包含了所有分页相关的元素 public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() throws JspException { // 没有标签体,要输出内容 JspWriter out = pageContext.getOut(); try { out.print(toHTML()); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } private String toHTML() { StringBuffer sb = new StringBuffer(); // 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在 // 上一次请求的URL sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>"); sb.append(" <input type='hidden' name='page'>"); // 上一次请求的参数 Map<String, String[]> paramMap = pageBean.getParamMap(); if(paramMap != null && paramMap.size() > 0) { Set<Entry<String, String[]>> entrySet = paramMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { // 参数名 String key = entry.getKey(); // 参数值 for (String value : entry.getValue()) { // 上一次请求的参数,再一次组装成了新的Form表单 // 注意:page参数每次都会提交,我们需要避免 if(!"page".equals(key)) { sb.append(" <input type='hidden' name='"+key+"' value='"+value+"' >"); } } } } sb.append("</form>"); // 分页条 sb.append("<ul class='pagination justify-content-center'>"); sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'"); sb.append(" href='javascript:gotoPage(1)'>首页</a></li>"); sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'"); sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'><</a></li>");// less than 小于号 // sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>"); // sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>"); sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>"); sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>"); sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>"); sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'"); sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>"); sb.append(" <li class='page-item go'><a class='page-link'"); sb.append(" href='javascript:skipPage()'>确定</a></li>"); sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>"); sb.append("</ul>"); // 分页执行的JS代码 sb.append("<script type='text/javascript'>"); sb.append(" function gotoPage(page) {"); sb.append(" document.getElementById('pageBeanForm').page.value = page;"); sb.append(" document.getElementById('pageBeanForm').submit();"); sb.append(" }"); sb.append(" function skipPage() {"); sb.append(" var page = document.getElementById('skipPage').value;"); sb.append(" if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+pageBean.maxPage()+") {"); sb.append(" alert('请输入1~"+pageBean.maxPage()+"的数字');"); sb.append(" return;"); sb.append(" }"); sb.append(" gotoPage(page);"); sb.append(" }"); sb.append("</script>"); return sb.toString(); } }
web
BookAction:
package com.lya.web; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lya.Dao.BookDao; import com.lya.entity.Book; import com.lya.util.PageBean; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; /** * 具体的子控制器 * * @author :JAVA-李永安 * * @date :2023年6月29日 下午7:39:52 */ public class BookAction extends ActionSupport implements ModelDriver<Book> { private Book book = new Book(); BookDao bookdao = new BookDao(); // 查询 public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception { PageBean pagebean = new PageBean(); pagebean.setRequest(req); List<Book> lst = bookdao.list(book, pagebean); System.out.println(lst);System.out.println("SFDa"); req.setAttribute("lst", lst); req.setAttribute("pagebean", pagebean); return "list"; } // 编辑跳转 /** * 跳转到新增修改页面 * @param req * @param resp * @return */ public String toEdit(HttpServletRequest req, HttpServletResponse resp) { try { /* * 如果是跳转修改页面,那么需要做bid条件的精准查询 */ if(book.getBid() != 0) { List<Book> list = bookdao.list(book, null); req.setAttribute("b", list.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 delete(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"; } /* * (non-Javadoc) * * @see com.zking.framework.ModelDriver#getModel() */ @Override public Book getModel() { // TODO Auto-generated method stub return null; } }
配置文件:
<?xml version="1.0" encoding="UTF-8"?> <config> <!-- 在这里每加一个配置,就相当于actions.put("/goods", new GoodsAction()); 这样就解决了代码灵活性的问题 --> <action path="/book" type="com.lya.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>
修改新增页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%> <%@ 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> </head> <body> <form class="form-inline" action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post"> 书籍ID:<input type="text" name="bid" value="${b.bid }"><br> 书籍名称:<input type="text" name="bname" value="${b.bname }"><br> 书籍价格:<input type="text" name="price" value="${b.price }"><br> <input type="submit"> </form> </body> </html>
显示页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%> <%@ 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> <!-- 这一行代码就相当于前面分页需求前端的几十行了 --> <z:page pageBean="${pageBean }"></z:page> </body> </html>
三.总结
1. 理解框架原理:通过学习自定义MVC框架,你将深入理解MVC框架的原理和设计思想。这有助于你对软件架构和设计模式的理解,使你能够更好地设计和构建可扩展、可维护和可测试的应用程序。
2. 定制化开发:自定义MVC框架允许你根据项目的特定需求进行定制化开发。你可以根据项目的规模、领域特点和技术需求进行框架的定制。这使你能够更好地满足项目的具体要求,提高开发效率和应用性能。
3. 学习框架扩展和集成:自定义MVC框架的学习将使你熟悉框架的核心组件和扩展机制。这使你具备了扩展框架功能和集成外部库和工具的能力。你可以根据需要添加新的功能、插件或集成其他的第三方库。
4. 代码可控性:通过自定义MVC框架,你能够更好地控制代码的质量和设计。你可以根据最佳实践和设计原则编写高质量、低耦合的代码,提高代码的可读性、可维护性和重用性。
我们使用了自定义框架就会极大的减少了代码的重复,提升开发效率。