通用分页2.0

一、改造pagebean

目标需求:
需要新增变量保存上一次查询条件
需要新增变量保存上一次请求地址
需要添加方法:获取最大页的页码
需要添加方法:获取下一页的页码
需要添加方法:获取上一页的页码
需要新增方法:初始化pagebean
PageBean类

package com.zsm.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;// 是否分页
	
//	 需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
	private String url;
	
//	 需要新增变量保存上一次查询条件
	private Map<String,String[]> parameterMap = new HashMap<>();
 
//	 需要添加方法:获取最大页的页码
	public int maxPage() {
		return this.total % this.rows == 0 ?
				this.total / this.rows
				: this.total / this.rows+1;
	}
 
//	 需要添加方法:获取上一页的页码;
	public int previousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}
 
	
//	 需要添加方法:获取下一页的页码	
	public int nextPage() {
		return this.page < this.maxPage()?
				this.page+1:this.page;
	}
 
//	 需要增加方法:初始化pagebean
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		this.setUrl(req.getRequestURI().toString());
		this.setParameterMap(req.getParameterMap());
	}
	
	private void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	
}
 
	private void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
}
 
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
	//		set自动生成的方法
			this.setPage(Integer.valueOf(page));
		}
	}
 
	
	
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}
 
	public void setParameterMap(Map<String, String[]> parameterMap) {
		this.parameterMap = parameterMap;
	}
 
	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
				+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
	}
 
	
}

然后再建立一个BookServlet :

package com.zsm.web;
 
import java.io.IOException;
import java.util.Map;
 
import javax.jws.WebService;
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.zsm.util.PageBean;
 
@WebServlet("/book/search")
public class BookServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
	
		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>

二、分页查询

案例
以书籍列表为例

<%@ 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>

前端首先要显示界面,自己建一个tag标签包(PageTag),然后通过自定义标签来写一个page标签,最后在index界面中直接写出自己定义的标签就行。
新建一个PageTag类

package com.zsm.tag;
 
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
 
import com.zsm.util.PageBean;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
 
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 (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.doStartTag();
	}
 
	private String toHTML() {
		StringBuffer sb=new StringBuffer();
//		隐藏的form表单,作用保存上一次查询条件
		sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
		sb.append("	<input type='hidden' name='page' value=''>");
		Map<String, String[]> parameterMap = pageBean.getParameterMap();
		if(parameterMap != null && parameterMap.size() > 0) {
			Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				String key = entry.getKey();// name/likes/page/rows
				String[] values = entry.getValue();
				if(!"page".equals(key)) {
					for (String value : values) {
						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()+")'>&lt;</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()+")'>&gt;</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");
		sb.append("				|| 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();
	}
}

继承 BodyTagSupport类,用stringbuffer中的append方法来实现页面展示效果。
最后在index中写好
ycx.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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>y</short-name>
  <uri>http://ycx.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.zsm.tag.PageTag</tag-class>
    
    <body-content>JSP</body-content>
   <attribute> 
   
        <name>pageBean</name>
       
        <required>true</required>
       
        <rtexprvalue>true</rtexprvalue>
    </attribute> 
  </tag>
 
</taglib>

分页得核心思想:当点击下一页时,有许多参数是不变的,比如像名字,行数,以及总页数,但是其中有一个参数要变,那就是page(页数)
优化PageBean代码:

package com.zsm.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;// 是否分页
	
//	 需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
	private String url;
	
//	 需要新增变量保存上一次查询条件
	private Map<String,String[]> parameterMap = new HashMap<>();
 
//	 需要添加方法:获取最大页的页码
	public int maxPage() {
		return this.total % this.rows == 0 ?
				this.total / this.rows
				: this.total / this.rows+1;
	}
 
//	 需要添加方法:获取上一页的页码;
	public int previousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}
 
	
//	 需要添加方法:获取下一页的页码	
	public int nextPage() {
		return this.page < this.maxPage()?
				this.page+1:this.page;
	}
 
//	 需要增加方法:初始化pagebean
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		this.setUrl(req.getRequestURI().toString());
		this.setParameterMap(req.getParameterMap());
	}
	
	private void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	
}
 
	private void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
}
 
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
	//		set自动生成的方法
			this.setPage(Integer.valueOf(page));
		}
	}
 
	
	
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}
 
	public void setParameterMap(Map<String, String[]> parameterMap) {
		this.parameterMap = parameterMap;
	}
 
	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
				+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
	}
 
	
}

紧接着在bookList.jsp内导入y标签和c标签:

package com.zsm.web;
 
import java.io.IOException;
import java.util.List;
import java.util.Map;
 
import javax.jws.WebService;
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.zsm.dao.BookDao;
import com.zsm.entity.Book;
import com.zsm.util.PageBean;
 
@WebServlet("/book/search")
public class BookServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		req.getParameter("name");
//		req.getParameterValues("likes");
		<input name="aa" value="">
//		Map<String, String[]> parameterMap = req.getParameterMap();//name
//	
		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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		req.setAttribute("pagebean", pageBean);
		req.getRequestDispatcher("/bookList.jsp").forward(req, resp);
	
	
	}
}

再利用c:forEach标签把数据遍历出来,展示在页面上去,
bookList.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@taglib uri="http://zsm.com" prefix="y" %>
	<%@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/search" 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>
			<c:forEach items="${books }" var="b">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
			</tr>
			</c:forEach>
		</tbody>
	</table>
	
	<y:page pageBean="${pagebean }"></y:page>
	
 
</body>
</html>

总结:通用分页把它简单化就分成前端和后台,其中公用的写到一个类里面就能减少代码量和大量时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值