1.框架配置
1.1将框架达成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
1.1.1将我们前面写的代码打成一个jar包然后导入我们的项目:
1.1.2 点击导出后我们搜索jar,点击JAR file(第一个选项):
1.1.3 然后自己把jar包放在自己清楚的路径里:
1.1.4最后我们把导出的jar包copy到WEB-INF安全目录下的lib文件夹中即可使用jar包中的方法。
2.增删改的方法
package com.xuyahui.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.xuyahui.util.DBAccess; import com.xuyahui.util.PageBean; /** * 所有Dao层的父类 * BookDao * UserDao * OrderDao * @author 86155 * * @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); 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(); } 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; } private String getCountSQL(String sql) { return "select count(1) from ("+sql+") t"; } private String getPageSQL(String sql,PageBean pageBean) { return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows(); } }
详细解析BaseDao方法
2.2增删改的方法
可以看到下面代码几乎都是两行带过
package com.xuyahui.dao; import java.util.List; import com.xuyahui.entity.Book; import com.xuyahui.util.BaseDao; import com.xuyahui.util.PageBean; import com.xuyahui.util.StringUtils; public class BookDao extends BaseDao<Book>{ /* 增删改查的通用套路 1.建立链接 2.预定义对象PreparedStatement 3.设置占位符的?的值 4.pst.executeUpdate(); 1. */ 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); } public static void main(String[] args) throws Exception { Book b = new Book(); b.setBid(2323); b.setBname("测试www"); b.setPrice(231f); BookDao bookDao = new BookDao(); // bookDao.delete(b); // bookDao.add(b); bookDao.edit(b); } }
3.配置文件
mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?> <config> <action path="/book" type="com.yinzi.Servlet.BookAction"> <forward name="list" path="/book.jsp" redirect="false" /> <forward name="toList" path="/book.action?methodName=list" redirect="true" /> <forward name="toEdit" path="/BookEdit.jsp" redirect="false" /> </action> </config>
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>mvc_crud</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>
.tid文件
<?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>xuyahui 1.1 core library</description> <display-name>xuyahui core</display-name> <tlib-version>1.1</tlib-version> <short-name>y</short-name> <uri>http://xuyahui</uri> <tag> <name>page</name> <tag-class>com.xuyahui.Tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
最后展示即可:
<%@ 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="${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>
效果图: