Servlet pager 封装分页控件
Servlet 目录:
web目录:
1、Person 实体类
package com.java.servlet.pager;
public class Person {
private String id;
private String name;
private int age;
private String sex;
private String address;
private String demo;
public Person() {
}
public Person(String id, String name, int age, String sex, String address, String demo) {
this();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
this.demo = demo;
}
public Person(String id, String name, int age, String sex, String address) {
this(id, name, age, sex, address, "");
}
public Person(String id, String name, int age, String sex) {
this(id, name, age, sex, "");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDemo() {
return demo;
}
public void setDemo(String demo) {
this.demo = demo;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + ", address=" + address + ", demo=" + demo
+ "]";
}
}
2、PagerServlet 模拟逻辑处理类
package com.java.servlet.pager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
public class PagerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
private void list(HttpServletRequest req, HttpServletResponse res) {
List<Person> persons = new ArrayList<Person>();
for (int i = 1; i < 30; i++) {
persons.add(new Person(String.valueOf(i), "name_" + i, 10 + i, (i % 2 == 0 ? "男" : "女"), "address_" + i, "demo_" + i));
}
String name = req.getParameter("name");
req.setAttribute("name", name);
String sex = req.getParameter("sex");
req.setAttribute("sex", sex);
for (int j = 0; j < persons.size(); j++) {
if (StringUtils.isNotEmpty(name) && !persons.get(j).getName().contains(name)) {
persons.remove(j);
j--;
continue;
}
if (StringUtils.isNotEmpty(sex)) {
if ("1".equals(sex) && "女".equals(persons.get(j).getSex())) {
persons.remove(j);
j--;
continue;
} else if ("2".equals(sex) && "男".equals(persons.get(j).getSex())) {
persons.remove(j);
j--;
continue;
}
}
}
int curPage = req.getParameter("curPage") == null ? 1 : Integer.parseInt(req.getParameter("curPage"));
if (curPage == 0) {
curPage = 1;
req.setAttribute("curPage", curPage);
}
int pageSize = 2;
req.setAttribute("pageSize", pageSize);
req.setAttribute("total", persons.size());
req.setAttribute("curPage", curPage);
if (persons.size() > 2) {
int lastIdx = curPage * pageSize;
if (lastIdx >= persons.size()) {
lastIdx = persons.size();
}
persons = persons.subList((curPage - 1) * pageSize, lastIdx);
}
req.setAttribute("persons", persons);
try {
//res.sendRedirect("pager.jsp"); //重定向不能带requset参数
req.getRequestDispatcher("pager.jsp").forward(req, res);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) {
String methodName = req.getParameter("method");
try {
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.setAccessible(true);
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、PagerTag Tag处理类
package com.java.servlet.pager;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
public class PagerTag extends BodyTagSupport {
private static final long serialVersionUID = -1848984466240909235L;
private int total;
private int pageSize;
private int curPage;
@Override
public int doStartTag() throws JspException {
if (pageSize == 0) {
System.out.println("Page size 不能为空!");
return Tag.SKIP_BODY;
}
//默认为第一页
if (curPage == 0) {
curPage = 1;
}
//没有分页时,设置为不可用
String navDisableStyle = "";
if (total == 0) {
navDisableStyle = " disabled=\"disabled\"";
}
int pageNum = (int) Math.ceil((double)total / pageSize);
System.out.println(pageNum);
String forwardClass = "";
if (curPage == pageNum) {
forwardClass = "class='disabled'";
}
String backClass = "";
if (curPage == 1) {
backClass = "class='disabled'";
}
StringBuilder sb = new StringBuilder();
sb.append("<nav aria-label=\"Page navigation\"" + navDisableStyle + ">\r\n" +
" <ul class=\"pagination\">\r\n" +
" <li " + backClass + ">\r\n" +
" <a href=\"javascript:doPage(1)\" aria-label=\"First\">\r\n" +
" <span aria-hidden=\"true\">«</span>\r\n" +
" </a>\r\n" +
" </li>" +
" <li " + backClass + ">\r\n" +
" <a href=\"javascript:doPage(" + (curPage - 1) + ")\" aria-label=\"Previous\" style=\"padding: 11px 13px 8px 13px;\" >\r\n" +
" <span aria-hidden=\"true\" style=\"font-family: cursive;font-size: 11px; font-weight: bold;\"><</span>\r\n" +
" </a>\r\n" +
" </li>");
if (pageNum > 14) {
if (curPage < 8) {
for (int i = 1; i < 8; i++) {
if (i == curPage) {
sb.append("<li class='active'><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
continue;
}
sb.append("<li><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
}
sb.append("<li class='disabled'><a href=\"javascript:void(0)\">•••</a></li>");
for (int i = pageNum - 7; i <= pageNum; i++) {
if (i == curPage) {
sb.append("<li class='active'><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
continue;
}
sb.append("<li><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
}
} else {
sb.append("<li class='disabled'><a href=\"javascript:void(0)\">•••</a></li>");
for (int i = pageNum - 14; i <= pageNum; i++) {
if (i == curPage) {
sb.append("<li class='active'><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
continue;
}
sb.append("<li><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
}
}
} else {
for (int i = 1; i <= pageNum; i++) {
if (i == curPage) {
sb.append("<li class='active'><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
continue;
}
sb.append("<li><a href=\"javascript:doPage(" + i + ")\">" + i + "</a></li>");
}
}
sb.append(" <li " + forwardClass + ">\r\n" +
" <a href=\"javascript:doPage(" + (curPage + 1) + ")\" aria-label=\"Next\" style=\"padding: 11px 13px 8px 13px;\">\r\n" +
" <span aria-hidden=\"true\" style=\"font-family: cursive;font-size: 11px; font-weight: bold;\">></span>\r\n" +
" </a>\r\n" +
" </li>\r\n" +
" <li " + forwardClass + ">\r\n" +
" <a href=\"javascript:doPage(" + pageNum + ")\" aria-label=\"Last\">\r\n" +
" <span aria-hidden=\"true\">»</span>\r\n" +
" </a>\r\n" +
" </li>\r\n" +
" </ul>\r\n" +
"</nav>");
sb.append("<script type=\"text/javascript\">\r\n" +
" function doPage(page){\r\n" +
" if((page >= " + pageNum + " && " + (curPage == pageNum) + ") || (page <= 1 && " + curPage + " == 1)) {" +
" return;" +
" }" +
" $(\"#curPage\").val(page);\r\n" +
" document.forms[0].submit();\r\n" +
" }\r\n" +
" </script>");
try {
this.pageContext.getOut().print(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
return Tag.SKIP_BODY;
//return Tag.EVAL_BODY_INCLUDE; //执行标签中的内容
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
}
页面中有使用到Bootstrap中的一些样式,自行网上下载。
4、pager.tld 定义标签
<?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>Show pager navigator</description>
<display-name>Pager navigator</display-name>
<tlib-version>1.1</tlib-version>
<short-name>p</short-name>
<uri>http://com.hsl.pager/core</uri>
<tag>
<name>pager</name>
<tag-class>com.java.servlet.pager.PagerTag</tag-class>
<body-content>empty</body-content>
<attribute>
<description>Data size</description>
<name>total</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Page size</description>
<name>pageSize</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Current page number</description>
<name>curPage</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
5、web.xml 配置Servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<servlet-name>PagerServlet</servlet-name>
<servlet-class>com.java.servlet.pager.PagerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PagerServlet</servlet-name>
<url-pattern>/pager.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>pager.jsp</welcome-file>
</welcome-file-list>
</web-app>
6、pager.jsp 页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://com.hsl.pager/core" prefix="p" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Pager.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css"
href="./css/lib/bootstrap.min.css">
<link rel="stylesheet" type="text/css"
href="./css/lib/bootstrap-theme.min.css">
<script type="text/javascript" src="./js/lib/jquery-3.3.1.js"></script>
<script type="text/javascript" src="./js/lib/bootstrap.js"></script>
</head>
<body>
<fieldset style="margin: 10px;">
<legend>Person信息列表:</legend>
<form class="form-inline">
<div class="form-group">
<label for="name">姓名</label> <input type="text"
class="form-control" id="name" name="name" value="${name}" placeholder="请输入姓名:">
</div>
<div class="form-group">
<label for="sex">性别</label>
<select name="sex" id="sex" class="form-control" >
<option value="0"></option>
<c:choose>
<c:when test="${sex == '1'}">
<option value="1" selected = "selected">男</option>
<option value="2">女</option>
</c:when>
<c:when test="${sex == '2'}">
<option value="1">男</option>
<option value="2" selected = "selected">女</option>
</c:when>
<c:otherwise>
<option value="1">男</option>
<option value="2">女</option>
</c:otherwise>
</c:choose>
</select>
</div>
<input type="hidden" name="curPage" value="1" id="curPage">
<input type="hidden" name="method" value="list">
<button type="submit" class="btn btn-default">查询</button>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>地址</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<c:forEach items="${persons}" var="person" varStatus="s">
<tr>
<td>${s.index}</td>
<td>${person.name}</td>
<td>${person.age}</td>
<td>${person.sex}</td>
<td>${person.address}</td>
<td>${person.demo}</td>
</tr>
</c:forEach>
<tr>
<td colspan="6" style="text-align: right;">
<p:pager pageSize="${pageSize}" curPage="${curPage}" total="${total}"/>
</td>
</tr>
</tbody>
</table>
</fieldset>
</body>
</html>
页面中有使用到 jstl-api-1.2.jar 标准标签库,请自行下载。