前言
利用自定义MVC框架优化中的代码进行打包,封装成自己的jar包,然后进行使用。
一、环境搭建
将之前写好的MVC导成jar包,方便使用,减少代码冗余,也提高了工作效率
接下来我们将导入我们的mvc.jar与其它相关jar包
将分页标签相关文件、及相关助手类导入
二、配置文件
1.中央控制器.xml
<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.xml中
2.mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <!-- 在这里每加一个配置,就相当于actions.put("/goods", new GoodsAction()); 这样就解决了代码灵活性的问题 --> <action path="/book" type="com.zking.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>
拿到增删改查最终的返回值判断重定向还是转发并进行跳转
三、实体与Dao方法的编写
实体--书类
package com.ctb.entity; /** * 实体--书 * @author biao * */ public class Book { private int bid; private String bname; private float price; 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; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } }
在这,我们先封装一个baseDao,做到通用分页模糊查询以及增删改的通用方法
package com.ctb.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; public class BaseDao<T> { /** * 通用的增删改方法 * @param book * @throws Exception */ public void 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); // pst.setObject(1, book.getBid()); // pst.setObject(2, book.getBname()); // pst.setObject(3, book.getPrice()); 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)); } 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))); } 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) { // pageSql=sql limit (page-1)*rows,rows return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows(); } }
接下来,咱们编写BookDao
package com.ctb.dao; import java.util.List; import com.ctb.entity.Book; import com.ctb.util.BaseDao; import com.ctb.util.PageBean; import com.ctb.util.StringUtils; public class BookDao extends BaseDao<Book>{ public void add(Book book) throws Exception { String sql = "insert into t_mvc_book values(?,?,?)"; super.executeUpdate(sql, book, new String[] {"bid","bname","price"}); } public void edit(Book book) throws Exception { String sql = "update t_mvc_book set bname = ?, price = ? where bid = ?"; super.executeUpdate(sql, book, new String[] {"bname","price","bid"}); } public void delete(Book book) throws Exception { String sql = "delete from t_mvc_book where bid = ?"; super.executeUpdate(sql, book, new String[] {"bid"}); } 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.isNotBlank(bname)) { sql += " and bname like '%"+bname+"%'"; } if (bid != 0) { sql +=" and bid = "+ bid; } return super.executeQuery(sql, Book.class, pageBean); } }
在BookDao中是不是能看出我们的方法仅需几行就解决了,这大大的提高了我们的效率呢
四、后台代码的编写
下面编写我们的servlet------BookAction
package com.ctb.servlet; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ctb.dao.BookDao; import com.ctb.entity.Book; import com.ctb.util.PageBean; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; /** * * @author biao * * 2023年7月3日:下午6:28:29 */ public class BookAction extends ActionSupport implements ModelDriver<Book>{ private Book book = new Book(); private BookDao bookDao = new BookDao(); @Override public Book getModel() { return book; } public String add(HttpServletRequest req, HttpServletResponse resp) { try { bookDao.add(book); } catch (Exception e) { e.printStackTrace(); } return "toList"; } public String list(HttpServletRequest req, HttpServletResponse resp) { try { PageBean pageBean = new PageBean(); pageBean.setRequest(req); List<Book> list = bookDao.list(book,pageBean); req.setAttribute("list", list); req.setAttribute("pageBean", pageBean); } catch (Exception e) { e.printStackTrace(); } return "list"; } public String delete(HttpServletRequest req, HttpServletResponse resp) { try { bookDao.delete(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"; } public String toEdit(HttpServletRequest req, HttpServletResponse resp) { try { //拿到id进行查询相应数据再跳转修改页面赋值 if(book.getBid() != 0) { List<Book> list = bookDao.list(book, null); req.setAttribute("b", list.get(0)); } } catch (Exception e) { e.printStackTrace(); } return "toEdit"; } }
在该类中它的返回值需要与我们配置文件中的mvc.xml中的name属性值一致
五、前台代码的编写
主界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://com.ctb" prefix="t"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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="请输入书籍名称"> <!-- 不想分页 --> <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="${list }"> <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> <t:page pageBean="${pageBean }"></t:page> </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> </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>
输出结果:
本篇文章就到这里啦,欢迎大家评论区讨论哦!😊😊