一,如何导出自定义MVC架包
导出步骤:
1.1 点击想导出的包并右键,点击Export,
1.2 搜索JAR file选中JAR file,点击Next
1.3 找到Browse...并选择你要将架包存储的位置,点击Finish即可
二,导入自定义架包(三步)
2.1 创建一个web项目,将所需要的架包复制到安全目录lib文件架中
2.2 将所需要的工具类导入utils
2.3 将子控制器配置文件导入根目录中
三,通用增删改查
3.1编写BaseDao
3.1.1前言:
优化分页及Dao方法,将之前所写的Dao方法重复的代码进行改善优化
BaseDao代码:
注意:将BaseDao定义成泛型
参数:编写的sql语句,实体,属性
package com.LiuBing.utils; 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层的父类 * ... * @author * * @param <T> */ public class BaseDao<T> { /** * 通用的增删改方法 * @param book * @return * @throws Exception */ public int 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)); } 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(); } }
所操作的对象---Book
定义一个Book实体:
package com.LiuBing.entity; /** * 实体类 * * @author 兵 * */ 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; } public Book(int bid, String bname, float price) { super(); this.bid = bid; this.bname = bname; this.price = price; } public Book() { super(); } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } }
将Dao方法继承BaseDao
package com.LiuBing.dao; import java.util.List; import com.LiuBing.entity.Book; import com.LiuBing.utils.BaseDao; import com.LiuBing.utils.PageBean; import com.LiuBing.utils.StringUtils; 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();//获取id //模糊查询 拼接查询所有语句 if(StringUtils.isNotBlank(bname)) { sql+=" and bname like '%"+bname+"%' "; } //当bid不为0 证明前端已经传来id值 if(bid!=0) { sql += "and bid ="+bid;//拼接 } return super.executeQuery(sql, Book.class, pageBean); } //增加方法 public int add(Book book) throws Exception{ //编写sql语句 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{ //编写sql语句 String sql ="delete from t_mvc_book where bid= ?"; return super.executeUpdate(sql, book,new String[] {"bid"}); } //修改方法 public int upd(Book book) throws Exception{ //编写sql语句 String sql ="update t_mvc_book set bname=?,price=? where bid=?"; return super.executeUpdate(sql, book,new String[] {"bname","price","bid"}); } }
3.2 编写优化Servlet
前端传增删改查等操作 继承ActionSupport(已经导jar) 实现ModelDriver(已导jar)
package com.LiuBing.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.LiuBing.dao.BookDao; import com.LiuBing.entity.Book; import com.LiuBing.utils.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(); PageBean pageBean = new PageBean(); public String list(HttpServletRequest req ,HttpServletResponse resp) { pageBean.setRequest(req); try { List<Book> list = bookdao.list(book, pageBean); req.setAttribute("list", list); req.setAttribute("pageBean", pageBean); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "list"; } //编辑页面 public String toEdit(HttpServletRequest req ,HttpServletResponse resp) { try { if(book.getBid()!=0) { List<Book> list = bookdao.list(book, null); req.setAttribute("b", list.get(0)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toEdit"; } //增加 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; } }
测试Dao方法:
package com.LiuBing.dao; import static org.junit.Assert.fail; import java.util.List; import org.junit.Test; import com.LiuBing.entity.Book; import com.LiuBing.utils.PageBean; public class BookDaoTest { private BookDao bookdao = new BookDao(); //测试增加方法 @Test public void testList() { System.out.println("123"); Book book = new Book(); PageBean pageBean = new PageBean(); // book.setBname("圣墟");//模糊查询 // pageBean.setPage(4);//分页查询 try { List<Book> list = bookdao.list(book, pageBean); /*for (int i = 0; i < list.size(); i++) { System.out.println(list[i]); }*/ for (Book book2 : list) { System.out.println(book2); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testAdd() { // Book book = new Book(56,"圣墟",520f); // try { // bookdao.add(book); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } @Test public void testDel() { // Book book = new Book(); // book.setBid(56); // // try { // bookdao.del(book); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } @Test public void testUpd() { Book book = new Book(56,"圣墟小子",520f); try { bookdao.upd(book); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.3 编写PageTag助手类(分页)
3.3.1标签助手类
代码:
package com.LiuBing.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.LiuBing.utils.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(); } }
3.3.2 自定义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.LiuBing.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3.3.3 jsp页面环境搭建(增删改查)
引入自定义标签库<%@ taglib prefix="z" uri="http://jsp.veryedu.cn"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!--导入自定义标签库 --> <%@ taglib prefix="z" uri="http://jsp.veryedu.cn"%> <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" 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 items="${list }" var="list"> <tr> <td>${list.bid }</td> <td>${list.bname }</td> <td>${list.price }</td> <td> <a href="${pageContext.request.contextPath }/book.action?methodName=toEdit$bid=${book.bid }">修改</a> <a href="${pageContext.request.contextPath }/book.action?methodName=del$bid=${book.bid }">删除</a> </td> </tr> </c:forEach> </tbody> </table> <!--导入自定义标签库 --> <z:page pageBean="${pageBean }"></z:page> </body> </html>
3.3.4 修改及新增jsp页面
为代码的简化,新增及修改跳的都是同一个页面,在Servlet进行判断,通过返回值点击的是哪个按钮进行不同的页面(一个修改带id值一个增加不要)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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"> <title>书记编辑页面</title> </head> <body> <form action="${pageContext.request.contextPath }/book.action?methodName=${not empty b ?'add': 'upd'}" method="post"> 编号:<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>