在web开发中,分页是必不可少的一部分,而且很多页面都会用到,所以将其公有化是一件很重要的事情
DEMO 2:
DEMO 3
代码示例:
使用了jstl标签 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
导入js <script type="text/javascript" src="js/pager-taglib.js"></script>
DEMO 1代码 <form action="servlet/PageServlet" method="get"> a_name:<input name="a_name" value="${a_name }" type="text" title="搜索条件1"><br/> b_name:<input name="b_name" value="${b_name }" type="text" title="搜索条件2"> <input type="submit" value="搜索"><br/><br/> <table class="data" border="1" cellpadding="5" cellspacing="0"> <tr> <td height="39">名字</td> <td height="39">数值</td> </tr> <c:forEach items="${pageModel.list }" var="data"> <tr> <td height="39">${data.name }</td> <td height="39">${data.value }</td> </tr> </c:forEach> </table> <br/> <jsp:include page="pager.jsp" flush="true"> <jsp:param name="url" value="servlet/PageServlet"/> <jsp:param name="items" value="${pageModel.totalCount }"/> <jsp:param name="params" value="name1:value1"/> <jsp:param name="params" value="name2:value2"/> </jsp:include> </form>
这里使用了jsp标签jsp:include,动态包含pager.jsp页,即分页部分抽取到了pager.jsp页面,只要为pager.jsp提供两个必须参数即可,修改分页样式时也只需修改pager.jsp里的每个a标签的样式即可
url;请求数据URL
items:总共记录数
params(可选):分页组件额外的参数,当无form标签时很有用
<jsp:include page="pager.jsp" flush="true"> <jsp:param name="url" value="servlet/PageServlet"/> <jsp:param name="items" value="${pageModel.totalCount }"/> <jsp:param name="params" value="name1:value1"/> <jsp:param name="params" value="name2:value2"/> </jsp:include>
pager.jsp的代码,可根据自行需要进行相应修改
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="pg_url" value='<%=request.getParameter("url")%>'></c:set> <c:set var="pg_items" value='<%=request.getParameter("items")%>'></c:set> <% String[] params = request.getParameterValues("params"); if(params != null){ Map<String,String> map = new HashMap<String,String>(); for(String param:params){ String[] strs= param.split(":"); map.put(strs[0], strs[1]); } pageContext.setAttribute("params", map); } %> <div class=" pager-taglib"> <pg:pager url="${pg_url }" items="${pg_items }" maxPageItems="${pagesize }" maxIndexPages="5" export="currentPageNumber=pageNumber,pageOffset" scope = "request"> <pg:index export="items,pages"> <c:if test="${!empty params}"> <c:forEach items="${params }" var="item"> <pg:param name="${item.key }" value="${item.value }"/> <input name="${item.key }" value="${item.value }" type="hidden"/> </c:forEach> </c:if> <span>共有${items }条记录</span> <span>当前第${currentPageNumber }页/共${pages }页</span> <pg:first><a href="${pageUrl }" onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;">首页</a></pg:first> <pg:prev><a href="${pageUrl }" onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;">前一页</a></pg:prev> <pg:pages> <c:choose> <c:when test="${currentPageNumber eq pageNumber }"> <font color="red">${pageNumber }</font> </c:when> <c:otherwise> <a href="${pageUrl }" onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;">${pageNumber }</a> </c:otherwise> </c:choose> </pg:pages> <pg:next> <a href="${pageUrl }" onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;">后一页</a> </pg:next> <pg:last> <a href="${pageUrl }" onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;">尾页</a> </pg:last> <pg:skip pages="${pageNumber }"> <input name="pager.offset" type="hidden" value="0" /> <input type="text" style="width: 50px;" number="${pageNumber}" value="${pageNumber}" pagesize="${pagesize }" pageOffset="${pageOffset }" pageCount="${pages }" onkeyup="this.value=this.value.replace(/[^\d]/g,'')" onafterpaste="this.value=this.value.replace(/[^\d]/g,'') " ></input> <a href="${pageUrl }" onclick="return tj(this)?pageSubmit(this):false;">跳转</a> </pg:skip> </pg:index> </pg:pager> </div>
pager-taglib.js的代码:
// pager-taglib.jar /** * 更改分页的请求方式,使之支持POST提交方式,当有FORM标签时为FORM标签的提交方式,否则为GET提交方式 * 使用时,只需在原来的每个标签上添加单击事件即可 * 一般:onclick="return setOffset(this,${pageNumber })?pageSubmit(this):true;" * 跳转:onclick="return tj(this)?pageSubmit(this):false;" */ function getParentDOM(obj){ var parent = obj.parentNode; if(parent.nodeName.toLowerCase()=="body"){ return document; } var className = parent.getAttribute("class"); if(className.indexOf("pager-taglib")==-1){ return getParentDOM(parent); } return parent; } /** * 一、跳转 * 二、设置submit提交时的pageOffset的值 */ function tj(obj){ var parent = getParentDOM(obj); var inputs = parent.getElementsByTagName('input'); var len = inputs.length; var offsetInput = inputs[len-2]; var pageUrl = obj.getAttribute("href"); var pageInput = inputs[len-1]; var pagesize = pageInput.getAttribute("pagesize"); var pageCount = pageInput.getAttribute("pageCount"); var oldOffsetValue = pageInput.getAttribute("pageOffset"); var oldPageValue = pageInput.getAttribute("number"); var newPageValue = pageInput.value; if(parseInt(newPageValue)<=0||parseInt(newPageValue)>pageCount){ alert('索引超出范围!'); pageInput.value = oldPageValue; pageInput.focus(); return false; } var newoffsetValue = (newPageValue-1)*pagesize; var newPageUrl = pageUrl.replace("pager.offset="+oldOffsetValue,"pager.offset="+newoffsetValue); obj.setAttribute("href",newPageUrl) offsetInput.value=newoffsetValue; return true; } /** * 提交页面 * @param obj 当前事件对象 * @returns */ function pageSubmit(obj){ var formDom = obj.parentNode; if(formDom.nodeName.toLowerCase()=='form'){ formDom.submit(); } else { if(formDom.nodeName.toLowerCase()=='body'){ return true; } return pageSubmit(formDom); } return false; } /** * 设置submit提交时的pageOffset的值 */ function setOffset(obj,pageNumber){ var parent = getParentDOM(obj); var inputs = parent.getElementsByTagName('input'); var len = inputs.length; var pageInput = inputs[len-1]; var offsetInput = inputs[len-2]; var pagesize = pageInput.getAttribute("pagesize");; var newoffsetValue = (pageNumber-1)*pagesize; offsetInput.value=newoffsetValue; return true; }
以上就是前台的设计了,下面给出后端代码:
过滤器代码:
package pager; import java.io.IOException; 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.http.HttpServletRequest; public class PagerFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; int offset = this.getOffset(request); int pagesize = this.getPagesize(request); SystemContext.setOffset(offset); SystemContext.setPageSize(pagesize); request.setAttribute("offset", offset); request.setAttribute("pagesize", pagesize); try { chain.doFilter(request, resp); } finally { SystemContext.removeOffset(); SystemContext.removePageSize(); } } protected int getOffset(HttpServletRequest request) { int offset = SystemContext.getOffset(); String strOffset = request.getParameter("pager.offset"); try { if (strOffset != null && !"".equals(strOffset)) { offset = Integer.parseInt(strOffset); } } catch (NumberFormatException e) {e.printStackTrace();} return offset; } protected int getPagesize(HttpServletRequest request) { int pagesize = SystemContext.getPageSize(); String strPagesize = request.getParameter("pagesize"); try { if (strPagesize != null && !"".equals(strPagesize)) { pagesize = Integer.parseInt(strPagesize); } } catch (NumberFormatException e) {e.printStackTrace();} return pagesize; } public void destroy() {} public void init(FilterConfig arg0) throws ServletException {} }
其中的SystemContext是为了方便的DAO层的获取,具体代码:
package pager; public class SystemContext { private static ThreadLocal<Integer> _offset = new ThreadLocal<Integer>(); private static ThreadLocal<Integer> _pagesize = new ThreadLocal<Integer>(); public static final int DEFAULT_PAGE_SIZE= 3; public static void setOffset(Integer offset) { _offset.set(offset); } public static void removeOffset() { _offset.remove(); } public static Integer getOffset() { Integer offset = _offset.get(); if (offset == null || offset < 0) { return 0; } return offset; } public static void setPageSize(Integer pagesize) { _pagesize.set(pagesize); } public static void removePageSize() { _pagesize.remove(); } public static Integer getPageSize() { Integer pagesize = _pagesize.get(); if (pagesize == null || pagesize < 0) { return DEFAULT_PAGE_SIZE; } return pagesize; } }
随便提供PageModel的代码,这个基本上都差不多
package pager; import java.util.List; public class PageModel<T> { private List<T> list; private int totalCount; // 总记录数 private int listSize; // 当前分页数据条数 private int pageCount; // 页数 public PageModel() { super(); } public PageModel(List<T> list, int totalCount) { super(); this.setList(list); this.totalCount = totalCount; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; this.listSize = list.size(); } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getListSize() { return listSize; } public int getPageCount() { if(totalCount > 0){ int pageSize = SystemContext.getPageSize(); pageCount = (totalCount-1)/(pageSize)+1; } return pageCount; } }
代码地址