1.理解分页思想
通用分页的核心思想可以总结为以下几个关键步骤:
- 确定每页显示的数据量:根据应用的需求,确定每页需要显示的数据量,例如每页显示10条数据。
- 计算总页数:根据数据总量和每页显示的数据量,计算出总页数。公式为:总页数 = 总数据量 / 每页显示的数据量。
- 用户界面呈现:在用户界面上显示分页控件,通常包括页码导航和上一页/下一页按钮等,以方便用户切换和导航不同的页面。
- 查询数据:根据用户选择的页面或页码,从数据源中查询相应页面的数据,通常使用相应的查询语句或API进行数据检索。
- 数据展示:将查询到的数据展示在用户界面上,以供用户浏览和交互。
也就是说,相较于上一次请求,只是页码改变了,其他查询条件并不变。
2.优化pagebean
优化pageBean的原因:
分页有很多东西不用改变,但是其中有一个参数要变,那就是page(页数),所以优化pageBean。即通用分页的核心思想。
优化前:
package com.Kissship.util; /** * 分页工具类 * */ public class PageBean { private int page = 1;// 页码 private int rows = 10;// 页大小 private int total = 0;// 总记录数 private boolean pagination = true;// 是否分页 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; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }
优化后:
package com.Kissship.util; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.Kissship.util.StringUtils; /** * 分页工具类 * */ public class PageBean { private int page = 1;// 页码 private int rows = 10;// 页大小 private int total = 0;// 总记录数 private boolean pagination = true;// 是否分页 // 增加一个url,保留上一次发送的请求地址 // 增加一个属性paramMap,保留上一次发送的请求携带的参数 // req.getParameterMap(); // 增加一个最大页的方法 // 增加一个下一页的方法 // 增加一个上一页的方法 // 初始化pagebean的方法 public int maxPage() {//最大页 return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1; } public int nextPage() {//下一页 return this.page < this.maxPage() ? this.page + 1 : this.page; } public int prevPage() {//上一页 return this.page > 1 ? this.page - 1 : this.page; } public void setRequest(HttpServletRequest req) { //初始化默认查询第几页的数据 this.setPage(req.getParameter("page")); this.setRows(req.getParameter("rows")); this.setPagination(req.getParameter("pagination")); //保留上一次的URL this.setUrl(req.getRequestURL().toString()); //保留携带的参数 this.setParamMap(req.getParameterMap()); } public void setPagination(String pagination) { if(StringUtils.isNotBlank(pagination)) this.setPagination(!"false".equals(pagination)); } public void setRows(String rows) { if(StringUtils.isNotBlank(rows)) this.setRows(Integer.valueOf(rows)); } public void setPage(String page) { if(StringUtils.isNotBlank(page)) this.setPage(Integer.valueOf(page)); } private String url; private Map<String, String[]> ParamMap; 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) { 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; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }
接下来我们新建一个BookServlet:
package com.Kissship.Servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; 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; /** * Servlet implementation class BookServlet */ @WebServlet("/book.action") public class BookServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @SuppressWarnings("unused") @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String bname = request.getParameter("bname"); // //map包含了浏览器传递到后台的所有参数键值对 // Map<String, String[]> map = request.getParameterMap(); // //浏览器请求的地址 // String url = request.getRequestURL().toString(); PageBean pageBean = new PageBean(); pageBean.setRequest(req); BookDao bookDao = new BookDao(); Book book = new Book(); book.setBname(req.getParameter("bname")); try { List<Book> books = bookDao.list2(book, pageBean); req.setAttribute("books", books); } catch (Exception e) { e.printStackTrace(); } req.setAttribute("pageBean", pageBean); req.getRequestDispatcher("bookList.jsp").forward(req, resp); } }
bookList.jsp代码:
<%@ 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>Insert title here</title> </head> <body> ${pagebean} </body> </html>
从Servlet运行结果:
3.分页案例演示
我们用书籍列表作为案例演示,如下:
<%@ 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"> <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" 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> </form> <table class="table table-striped "> <thead> <tr> <th scope="col">书籍ID</th> <th scope="col">书籍名</th> <th scope="col">价格</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>圣墟第1章</td> <td>1</td> </tr> <tr> <td>1</td> <td>圣墟第1章</td> <td>1</td> </tr> </tbody> </table> </body> </html>
目前我们的页面效果是这样的,数据暂时都是无效的定死的数据,并且无法查看上一页,下一页和尾页,所以我们还需要进行改写:
3.1PageTag助手类:
package com.Kissship.tag; import java.io.IOException; import java.util.Map; 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; /** * PageTag.java * @author jj * */ 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 SKIP_BODY; } private String toHTML() { StringBuilder sb = new StringBuilder(); // 这里拼接的是一个上一次发送的请求以及携带的参数,唯一改变的就是页码 sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); sb.append("<input type='hidden' name='methodName' value='list'>"); sb.append("<input type='hidden' name='page'>"); // 重要设置拼接操作,将上一次请求参数携带到下一次 Map<String, String[]> paMap = pageBean.getParamMap(); if(paMap !=null && paMap.size()>0){ Set<Map.Entry<String, String[]>> entrySet = paMap.entrySet(); for (Map.Entry<String, String[]> entry : entrySet) { for (String val : entry.getValue()) { if(!"page".equals(entry.getKey())){ sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>"); } } } } sb.append("</form>"); int page = pageBean.getPage(); int max = pageBean.maxPage(); int before = page > 4 ? 4 : page-1; int after = 10 - 1 - before; after = page+after > max ? max-page : after; // disabled boolean startFlag = page == 1; boolean endFlag = max == page; // 拼接分页条 sb.append("<ul class='pagination'>"); sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage(1)'>首页</a></li>"); sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.prevPage()+")'><</a></li>"); // 代表了当前页的前4页 for (int i = before; i > 0 ; i--) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page-i)+")'>"+(page-i)+"</a></li>"); } sb.append("<li class='page-item active'><a class='page-link' href='javascript:gotoPage("+pageBean.getPage()+")'>"+pageBean.getPage()+"</a></li>"); // 代表了当前页的后5页 for (int i = 1; i <= after; i++) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page+i)+")'>"+(page+i)+"</a></li>"); } sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>"); sb.append("<li class='page-item "+(endFlag ? "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' type='text' id='skipPage' name='' /><b>页</b></li>"); sb.append("<li class='page-item go'><a class='page-link' 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) > "+max+") {"); sb.append("alert('请输入1~N的数字');"); sb.append("return;"); sb.append("}"); sb.append("gotoPage(page);"); sb.append("}"); sb.append("</script>"); return sb.toString(); } }
3.2tld配置文件
<?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>JSTL 1.1 core library</description> <display-name>JSTL core</display-name> <tlib-version>1.1</tlib-version> <short-name>z</short-name> <uri>http://www/Kissship/com</uri> <validator> <description> Provides core validation features for JSTL tags. </description> <validator-class> org.apache.taglibs.standard.tlv.JstlCoreTLV </validator-class> </validator> <tag> <name>page</name> <tag-class>com.Kissship.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3.3分页自定义jsp标签
根据需要遍历的目标进行JSP标签的自定义(这里是page页码)
代码如下:
<?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>JSTL 1.1 core library</description> <display-name>JSTL core</display-name> <tlib-version>1.1</tlib-version> <short-name>z</short-name> <uri>http://www/Kissship/com</uri> <validator> <description> Provides core validation features for JSTL tags. </description> <validator-class> org.apache.taglibs.standard.tlv.JstlCoreTLV </validator-class> </validator> <tag> <name>page</name> <tag-class>com.Kissship.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3.4BookList
紧接着在bookList中导入z标签和c标签:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www/Kissship/com" prefix="z"%>
最后把它们遍历出来再加上我们的bookServlet展示在页面上就可以了。
页面代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www/Kissship/com" prefix="z"%> <!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> ${pageBean } <form class="form-inline" action="${pageContext.request.contextPath }/book.action" 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> </form> <table class="table table-striped bg-success"> <thead> <tr> <th scope="col">书籍ID</th> <th scope="col">书籍名</th> <th scope="col">价格</th> </tr> </thead> <tbody> <c:forEach items="${books }" var="b"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> </tr> </c:forEach> </tbody> </table> <z:page pageBean="${pageBean }"></z:page> </body> </html>
3.5BookServlet
package com.Kissship.Servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; 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; /** * Servlet implementation class BookServlet */ @WebServlet("/book.action") public class BookServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @SuppressWarnings("unused") @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String bname = request.getParameter("bname"); // //map包含了浏览器传递到后台的所有参数键值对 // Map<String, String[]> map = request.getParameterMap(); // //浏览器请求的地址 // String url = request.getRequestURL().toString(); PageBean pageBean = new PageBean(); pageBean.setRequest(req); BookDao bookDao = new BookDao(); Book book = new Book(); book.setBname(req.getParameter("bname")); try { List<Book> books = bookDao.list2(book, pageBean); req.setAttribute("books", books); } catch (Exception e) { e.printStackTrace(); } req.setAttribute("pageBean", pageBean); req.getRequestDispatcher("bookList.jsp").forward(req, resp); } }
3.6乱码问题
在进行页面输出或搜索书籍的时候,我们会发现可能出现乱码问题,这时候我们只需要加上一个过滤器就ok了。
如下:
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(); } } }
最后页面的输出结果如下:
4.如何debug调试代码
4.1debug启动项目
操作方式如下:
4.2在将要调试的代码上打上断点
在代码行数显示的左侧双击两下鼠标左键即可打上断点。
如下:
双击左键也可取消断点,在执行代码时也可以禁用断点。
注意:
断点可以影响代码执行。在调试过程中,我们可以在代码中设置断点,当程序执行到断点所在的位置时,程序会中断执行,进入调试模式,以便我们进行代码分析、变量查看、单步调试等操作。
当程序执行到断点时,程序会停止在该处,暂停执行。这样可以方便我们观察程序在执行到该点时的状态,包括变量的值、执行路径等。我们可以逐行地执行代码,查看每一行代码的执行情况,理解程序的运行过程,找出潜在的错误或问题。
断点可以在开发和调试阶段使用,帮助我们定位和解决代码中的问题。但是需要注意,在生产环境中不应该保留断点,因为它们会影响代码的正常执行,并且可能导致系统的性能下降。因此,在发布到生产环境之前,务必要移除或禁用所有的断点。
最后J2EE之通用分页(下)就到这里,祝大家在敲代码的路上一路通畅!