1.框架配置
1.1将框架达成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
将我们前面写的代码打成一个jar包然后导入我们的项目:
点击导出后我们搜索jar,点击JAR file(第一个选项):
然后自己把jar包放在自己清楚的路径里:
之后我们把导出的jar包copy到WEB-INF安全目录下的lib文件夹中即可使用jar包中的方法。
1.2在这之后呢我们只需要导入其他的和依赖(助手类、baseDao······)
tag:
package com.Kissship.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.Kissship.util.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(); } }
BaseDao:
package com.Kissship.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; /** * BaseDao 所有Dao类的父亲 * @author jj * * @param <T> */ public class BaseDao<T> { /* * 通用增删改方法 * sql---->增删改SQL * t---->SQL中的表对应的实体类 * attrs---->实体类对应的属性 * */ 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(); } }
PageBean:
package com.Kissship.util; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * 分页工具类 * */ public class PageBean { private int page = 1;// 页码 private int rows = 10;// 页大小 private int total = 0;// 总记录数 private boolean pagination = true;// 是否分页 private String url; //保存上一次请求的URL private Map<String,String[]> paramMap = new HashMap<>();// 保存上一次请求的参数 /** * 初始化pagebean的,保存上一次请求的重要参数 * @param req */ public void setRequest(HttpServletRequest req) { // 1.1 需要保存上一次请求的URL this.setUrl(req.getRequestURL().toString()); // 1.2 需要保存上一次请求的参数 bname、price this.setParamMap(req.getParameterMap()); // 1.3 需要保存上一次请求的分页设置 pagination this.setPagination(req.getParameter("pagination")); // 1.4 需要保存上一次请求的展示条目数 this.setRows(req.getParameter("rows")); // 1.5 初始化请求的页码 page this.setPage(req.getParameter("page")); } public void setPage(String page) { if(StringUtils.isNotBlank(page)) this.setPage(Integer.valueOf(page)); } public void setRows(String rows) { if(StringUtils.isNotBlank(rows)) this.setRows(Integer.valueOf(rows)); } public void setPagination(String pagination) { // 只有在前台jsp填写了pagination=false,才代表不分页 if(StringUtils.isNotBlank(pagination)) this.setPagination(!"false".equals(pagination)); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getParamMap() { return paramMap; } public void setParamMap(Map<String, String[]> paramMap) { this.paramMap = paramMap; } public PageBean() { super(); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } /** * 获得起始记录的下标 * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } /** * 最大页 * @return */ public int maxPage() { // total % rows == 0 ? total / rows : total / rows +1 return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1; } /** * 下一页 * @return */ public int nextPage() { // 如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1 return this.page < this.maxPage() ? this.page + 1 : this.page; } /** * 上一页 * @return */ public int previousPage() { return this.page > 1 ? this.page - 1 : this.page; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }
DBAccess:
package com.Kissship.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 提供了一组获得或关闭数据库对象的方法 * */ public class DBAccess { private static String driver; private static String url; private static String user; private static String password; static {// 静态块执行一次,加载 驱动一次 try { InputStream is = DBAccess.class .getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("pwd"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 获得数据连接对象 * * @return */ public static Connection getConnection() { try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs) { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs) { close(rs); close(stmt); close(conn); } public static boolean isOracle() { return "oracle.jdbc.driver.OracleDriver".equals(driver); } public static boolean isSQLServer() { return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver); } public static boolean isMysql() { return "com.mysql.cj.jdbc.Driver".equals(driver); } public static void main(String[] args) { Connection conn = DBAccess.getConnection(); System.out.println(conn); DBAccess.close(conn); System.out.println("isOracle:" + isOracle()); System.out.println("isSQLServer:" + isSQLServer()); System.out.println("isMysql:" + isMysql()); System.out.println("数据库连接(关闭)成功"); } }
过滤器:
package com.Kissship.util; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 中文乱码处理 * */ @WebFilter("*.action") public class EncodingFiter implements Filter { private String encoding = "UTF-8";// 默认字符集 public EncodingFiter() { super(); } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // 中文处理必须放到 chain.doFilter(request, response)方法前面 res.setContentType("text/html;charset=" + this.encoding); if (req.getMethod().equalsIgnoreCase("post")) { req.setCharacterEncoding(this.encoding); } else { Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合 Set set = map.keySet();// 取出所有参数名 Iterator it = set.iterator(); while (it.hasNext()) { String name = (String) it.next(); String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组] for (int i = 0; i < values.length; i++) { values[i] = new String(values[i].getBytes("ISO-8859-1"), this.encoding); } } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集 if (null != s && !s.trim().equals("")) { this.encoding = s.trim(); } } }
StringUtils:
package com.Kissship.util; public class StringUtils { // 私有的构造方法,保护此类不能在外部实例化 private StringUtils() { } /** * 如果字符串等于null或去空格后等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isBlank(String s) { boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isNotBlank(String s) { return !isBlank(s); } }
1.3框架的配置文件添加、以及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>Kissship_mvc_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>
2.通用增删改
通过最近的学习,发现我之前写增删改查的代码很繁琐而且有待改进。可以利用自定义MVC框架来做到简化冗余代码的同时实现与之相同的功能。这是我的学习代码(以书籍管理系统为例),如下:
首先我们要新建一个Book实体类:
package com.Kissship.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; } 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方法了,这里我注释的是繁琐的代码,没注释的则是优化后的代码,如下:
Dao方法:
package com.Kissship.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.Kissship.entity.Book; import com.Kissship.util.BaseDao; import com.Kissship.util.DBAccess; import com.Kissship.util.PageBean; import com.Kissship.util.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(); if (StringUtils.isNotBlank(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()); */ // 增加 // 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 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 edit(Book book) throws SQLException { // 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 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 = ?"; 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 = ?"; return super.executeUpdate(sql, book, new String[] { "bname", "price", "bid" }); } }
可以看到优化后的代码很明显变得简短很多。紧接着我们用JUnit来测试一下:
BookDAoTest:
package com.Kissship.dao; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import com.Kissship.entity.Book; import com.Kissship.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> lst = bookDao.list(book, pageBean); for (Book b : lst) { System.out.println(b); } } catch (Exception e) { e.printStackTrace(); } } // @Test // public void testAdd() { // Book book = new Book(150141318,"嘿嘿",99); // try { // bookDao.add(book); // } catch (Exception e) { // e.printStackTrace(); // } // } // @Test // public void testDel() { // Book book = new Book(); // book.setBid(150141318);//删除id为150141318的数据 // try { // bookDao.del(book); // } catch (Exception e) { // e.printStackTrace(); // } // } @Test public void testEdit() { Book book = new Book(150141318,"被修改了啊啊啊",999); try { bookDao.edit(book); } catch (Exception e) { e.printStackTrace(); } } }
可以看到我们添加了一条名字为"嘿嘿"的数据,效果图如下:
接着我们试着删除它,如下:
最后试着修改:
经过测试之后没问题,我们通用增删改也就编写完成了。
3.后台代码
新建一个BookAction类:
package com.Kissship.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.Kissship.dao.BookDao; import com.Kissship.entity.Book; import com.Kissship.util.PageBean; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriven; public class BookAction extends ActionSupport implements ModelDriven<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> lst = bookDao.list(book, pageBean); req.setAttribute("lst", lst); req.setAttribute("pageBean", pageBean); } catch (Exception e) { e.printStackTrace(); } return "list"; } // 编辑界面跳转--bookEdit.jsp public String toEdit(HttpServletRequest req, HttpServletResponse resp) { try { if (book.getBid() != 0) { List<Book> lst = bookDao.list(book, null); req.setAttribute("lst", lst.get(0)); } } catch (Exception e) { e.printStackTrace(); } return "toEdit"; } // 增加--重定向到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 edit(HttpServletRequest req, HttpServletResponse resp) { try { bookDao.edit(book); } catch (Exception e) { e.printStackTrace(); } return "toList"; } @Override public Book getModel() { return book; } }
在写完BookAction类之后把它的路径名放进我们的xml配置文件中,如下:
mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <config> <action path="/book" type="com.Kissship.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>
4.前端代码
在我们的后台代码写完之后,需要把我们的效果在浏览器上显示出来,也就需要我们完善前端的代码,如下:
copy我们之前写过的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> <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="${lst }"> <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=del&bid=${b.bid}">删除</a> </td> </tr> </c:forEach> </tbody> </table> <!-- 这一行代码就相当于前面分页需求前端的几十行了 --> <z:page pageBean="${pageBean }"></z:page> </body> </html>
bookEdit:
<%@ 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=${empty b ? 'add' : 'edit'}" 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"><br> </form> </body> </html>
效果图:
最后自定义MVC增删改查(终极篇)就到这里,祝大家在敲代码的路上一路通畅!