目录
一、前言
二、导出自定义MVC架包
三、使用自定义MVC架包
四、优化增删改查Dao层及Servlet
1.优化增删改查Dao层
2.优化增删改查Servlet代码
五、案例实操
1.将PageTag自定义标签进行配置
2.jsp页面环境搭建
3.案例演示
一、前言
在上篇中,我们已经优化了子控制器初始化、跳转页面的代码冗余以及请求参数进行实体封装的三大问题,目前我们的自定义MVC已经可以满足绝大部分需求了,下面我来带领大家使用我们的自定义MVC架包以及CRUD操作的优化。
(以下的所有代码我都会上传CSDN欢迎下载或者翻阅前两篇博客也可以)
二、导出自定义MVC架包
首先,使用之前,我们必须先将我们所写的自定义MVC导出jar文件才行。
第一步:找到有关自定义MVC的包
我们的framework与model包
第二步:右击Export导出
第三步:选择JAR file文件
第四步:选择自己需要存放的位置进行保存一键Finish即可
这样我们所写的自定义MVC架包就做好啦!!
三、使用自定义MVC架包
①建立一个web项目,将所需要的架包导入(特别是我们自己所写的架包)
②建立工具包(utils)将所需的文件导入
注意:这里最好测试一下我们的数据库帮助类(DBAccess),是否连接数据库成功
③导入我们的mvc.xml子控制配置文件
最好新建一个Source Folder资源包进行保存
<?xml version="1.0" encoding="UTF-8"?> <config> <action path="/book" type="com.zking.web.BookAction"> <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>
这里的xml配置文件与自定义MVC架构【中】的有所不同,因为增删改查操作需要有三种情况,第一种查询界面、第二种修改初始化数据界面、第三种增删改操作执行过后调用list方法先同步数据再进行回显。
④web.xml文件手动配置中央控制器(DispatchServlet)
<?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>xmymvc_crud</display-name> <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>
温馨提示:
因为以前我们是在中央控制器(DispatchServlet)进行注解的方式进行拦截servlet请求的操作并完成初始化配置,但是现在中央控制器(DispatchServlet)是架包里面的东西了所以需要手动配置需要解析的xml文件(/mvc.xml)。
四、优化增删改查Dao层及Servlet
1.优化增删改查Dao层
创建数据库实体以及dao包
实体类
package com.zking.entity; 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 + "]"; } }
这里我们就可以优化我们的Dao层代码了,将增删改融为一个代码。
增删改查的通用套路
1.建立链接
2.预定义对象PreparedStatement
3.设置占位符的?的值
4.pst.executeUpdate();所以我们可以将重复的代码和思维进行优化
BaseDao(通用的增删改查)
package com.zking.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.zking.entity.Book; import com.zking.util.DBAccess; import com.zking.util.PageBean; import com.zking.util.StringUtils; /** * 所有Dao层的父类 * BookDao * UserDao * OrderDao * ... * @author Administrator * * @param <T> */ public class BaseDao<T> { /** * 通用的增删改方法 * @param book * @throws Exception */ public void executeUpdate(String sql, T t, String[] attrs) throws Exception { Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); /* * 思路: * 1.从传进来的t中读取属性值 * 2.往预定义对象中设置了值 */ 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 { 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) { return "select count(1) from ("+sql+") t"; } /** * 将原生SQL转换成pageSQL * @param sql * @param pageBean * @return */ private String getPageSQL(String sql,PageBean pageBean) { return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows(); } }
BookDao继承BaseDao
package com.zking.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.zking.entity.Book; import com.zking.util.BaseDao; import com.zking.util.DBAccess; import com.zking.util.PageBean; import com.zking.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(); if(StringUtils.isNotBlank(bname)) { sql += " and bname like '%"+bname+"%'"; } return super.executeQuery(sql, Book.class, pageBean); } }
2.优化增删改查Servlet代码
创建一个Servlet继承ActionSupport并实现ModelDriver<需要操作的实体>
package com.zking.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zking.dao.BookDao; import com.zking.entity.Book; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; import com.zking.util.PageBean; /** * @author Java方文山 * */ 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.setPagination(true); pageBean.setRequest(req); List<Book> list = bookDao.list(book,pageBean); req.setAttribute("books", 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"; } /** * 跳转到新增修改页面 * @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"; } }
因为前面也说到了,我们有三种跳转情况,所以我们return的值也有三种(注意配置好xml文件)
五、案例实操
1.将PageTag自定义标签进行配置
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>zking 1.1 core library</description> <display-name>zking core</display-name> <tlib-version>1.1</tlib-version> <short-name>zking</short-name> <uri>http://jsp.veryedu.cn</uri> <tag> <name>page</name> <tag-class>com.zking.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
放入web-inf目录下
2.jsp页面环境搭建
首页bookList.jsp
<%@ 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> <c:if test="${empty pageBean}"> <jsp:forward page="${pageContext.request.contextPath }/book.action?methodName=list"></jsp:forward> </c:if> <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="true" 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 "> <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="${books }"> <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>
修改/新增页面bookEdit.jsp
<%@ 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>
3.案例演示
看到这,我相信你对自定义MVC一定有自己的独特理解了!!
至此自定义MVC三部曲完结!!