1.什么是自定义MVC:
自定义MVC框架是一种开发模式,用于构建Web应用程序。MVC代表模型(Model)、视图(View)和控制器(Controller),它提供了一种结构化的方法来组织和管理代码。
自定义MVC框架意味着你可以根据自己的需求和偏好,从头开始构建一个适合项目的MVC框架,而不是使用现成的框架。
自定义MVC框架的主要组成部分包括:
- 模型(Model):模型负责处理应用程序的数据逻辑,包括数据库操作、数据验证等。
- 视图(View):视图负责处理与用户界面相关的逻辑,它呈现模型中的数据给用户,并接收用户的输入。
- 控制器(Controller):控制器负责处理用户的请求,根据请求调用相关的模型和视图,并返回适当的响应给用户。
- 自定义MVC框架的优点包括:
- 灵活性:你可以根据项目需求和团队技术水平,定制框架的各个组件,使其更符合项目的需求。
- 可扩展性:自定义框架可以根据项目的规模和功能需求进行扩展,灵活地添加或修改功能。
2.将框架打成jar包,然后导入新工程,并且把框架依赖的jar包导入进去:
1.选中要导成jar包的类然后右键选中导出:
2.点击导出后在搜索框搜索jar。
然后导入到桌面 就可以用了
3.将分页标签相关文件,及相关助手类导入:
建立一个util包和tag包:
然后找到前面写的类导入进去:
4.框架的配置文件添加,以及web.xml的配置-以后开源框架的使用从这一步开始,完成mvc.xml的配置
2.配置web.xml文件:
3.配置mvc.xml文件:
5.完成Book实体类及bookdao的编写:6.完成通用增删改方法:
1.编写Book实体类:
baseDao编写:
package com.xy.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; import com.xy.entity.Book; import com.xy.util.DBAccess; import com.xy.util.PageBean; import com.xy.util.StringUtils; /** * 所有Dao层的父类 * BookDao * UserDao * OrderDao * ... * @author Administrator * * @param <T> */ public class BaseDao<T> { /*** * 通用的增删改方法 * * @param sql 增删改sql * @param t sql中的表对应的实体类 * @param attrs 实体类对应的属性 * @return */ public int executeupdate(String sql,T t,String[] attrs) throws Exception { Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); for (int i = 0; i < attrs.length; i++) { Field f = t.getClass().getDeclaredField(attrs[i]); f.setAccessible(true); ps.setObject(i+1, f.get(t)); } return ps.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(); } }
BookDao继承baseDao之后的编写:
package com.xy.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.xy.entity.Book; import com.xy.util.BaseDao; import com.xy.util.DBAccess; import com.xy.util.PageBean; import com.xy.util.StringUtils; import jdk.nashorn.internal.runtime.regexp.joni.constants.OPSize; public class BookDao extends BaseDao<Book>{ //查询 public List<Book> list(Book book, PageBean pageBean) throws Exception { String sql="select * from t_mvc_book where 1=1"; String bname = book.getBname(); int bid = book.getBid(); if(StringUtils.isBlank(bname)) { sql +=" and bname like '%"+bname+"%'"; } //bid==0意味着前台没有传递bid if(bid !=0) { sql +=" and bid =" + bid; } return super.executeQuery(sql, Book.class, pageBean); } /** *1.重复代码 * Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); 2.代码逻辑是重复的,就是将sql中的占位符赋值 ps.setObject(1, book.getBid()); ps.setObject(2, book.getBname()); ps.setObject(3, book.getPrice()); * @param book * @return * @throws Exception */ //增加 // public int add(Book book) throws Exception { // String sql ="insert into t_mvc_book values(?,?,?)"; // Connection conn = DBAccess.getConnection(); // PreparedStatement ps = conn.prepareStatement(sql); // ps.setObject(1, book.getBid()); // ps.setObject(2, book.getBname()); // ps.setObject(3, book.getPrice()); // return ps.executeUpdate(); // } 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"}); } //删除 // public int del(Book book) throws Exception { // String sql ="delete from t_mvc_book where bid=?"; // Connection conn = DBAccess.getConnection(); // PreparedStatement ps = conn.prepareStatement(sql); // ps.setObject(1, book.getBid()); // return ps.executeUpdate(); // } public int del(Book book) throws Exception { String sql ="delete from t_mvc_book where bid=?"; return super.executeupdate( sql, book, new String[] {"bid"}); } //修改 // public int edit(Book book) throws Exception { // String sql ="update t_mvc_book set bname =?,price=?,where bid=?"; // Connection conn = DBAccess.getConnection(); // PreparedStatement ps = conn.prepareStatement(sql); // ps.setObject(1, book.getBname()); // ps.setObject(2, book.getPrice()); // ps.setObject(3, book.getBid()); // return ps.executeUpdate(); // } public int upd(Book book) throws Exception { String sql ="update t_mvc_book set bname =?,price=?,where bid=?"; return super.executeupdate( sql, book, new String[] {"bname","price","bid"}); } }
测试:
双击BookDao (ctrl+n)弹出窗口搜索jun然后点击第一个:
它会跳到一个BookDaoTest的类:增删改查测试,代码如下
package com.xy.dao; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import com.xy.entity.Book; import com.xy.util.PageBean; public class BookDaoTest { private BookDao bookDao =new BookDao(); @Test public void testList() { Book book=new Book(); book.setBname("圣墟"); PageBean pageBean=new PageBean(); // pageBean.setPage(3); //不想分页 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(10,"圣墟10",10f); try { bookDao.add(book); } catch (Exception e) { e.printStackTrace(); } } @Test public void testDel() { Book book=new Book(); book.setBid(10); try { bookDao.del(book); } catch (Exception e) { e.printStackTrace(); } } @Test public void testUpd() { Book book =new Book(10,"圣墟10张",10f); try { bookDao.add(book); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
查看所有结果如下:
7.完成BookAction:
package com.xy.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xy.dao.BookDao; import com.xy.entity.Book; import com.xy.util.PageBean; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; public class BookAction extends ActionSupport implements ModelDriver<Book> { private Book book=new Book(); private BookDao bookDao=new BookDao(); // 查询 booklist.jsp public String list(HttpServletRequest req, HttpServletResponse resp) { PageBean pageBean=new PageBean(); pageBean.setRequest(req); try { List<Book> l = bookDao.list(book, pageBean); req.setAttribute("l", l); req.setAttribute("pageBean", pageBean); } catch (Exception e) { e.printStackTrace(); } return "list"; } // 编辑界面跳转 bookupd.jsp public String toupd(HttpServletRequest req, HttpServletResponse resp) { try { if(book.getBid()!=0) { List<Book> l = bookDao.list(book, null); req.setAttribute("b", l.get(0)); } } catch (Exception e) { e.printStackTrace(); } return "toupd"; } // 增加 重定向到http://localhost:8080/mvc/book.action?methodName=list 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 upd(HttpServletRequest req, HttpServletResponse resp) { try { bookDao.upd(book); } catch (Exception e) { e.printStackTrace(); } return "tolist"; } @Override public Book getModel() { return book; } }
8.完成前台代码编写
建立一个书籍编辑界面(修改/新增共用):
建立一个booklist:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://jsp.xiaoye.xy" prefix="x" %> <!DOCTYPE html > <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="请输入书籍名称"> </div> <button type="submit" class="btn btn-primary mb-2">查询</button> <a class="btn btn-primary mb-2"s href="${pageContext.request.contextPath }/book.action?methodName=toupd&bid=${b.bid }" >新增</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 items="${l }" var="b"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> <td> <a href="${pageContext.request.contextPath }/book.action?methodName=toupd&bid=${b.bid }" >修改</a> <a href="${pageContext.request.contextPath }/book.action?methodName=del&bid=${b.bid }" >删除</a> </td> </tr> </c:forEach> </tbody> </table> <!--这一行代码代表了HTML 分页条 JS From --> <x:page pageBean="${pageBean }"></x:page> </body> </html>