Java封装分页组件,在JSP中进行分页

分页离不开两个必须的量①当前页②每页显示几条记录,有了这两个量,就可以构建分页所需的各种量了,如总页数,页面页码的开始索引,结束索引等。

一、分页组件

package edu.njcit.action;

import java.util.List;
/**
 * 分页组件
 * @author Administrator
 * @param <T>
 */
public class PageView<T> {
	/** 分页数据 **/
	private List<T> records;
	/** 页码开始索引和结束索引 **/
	private PageIndex pageindex;
	/** 总页数 **/
	private long totalpage = 1;
	/** 每页显示记录数,默认12 **/
	private int recordPerPage=12;
	/** 当前页 **/
	private int currentpage = 1;
	/** 总记录数 **/
	private long totalrecord;
	/** 页码数量,默认10 **/
	private int pagecode = 10;
	/** 获取记录的开始索引 **/
	public int getStartRecordIndex() {
		return (this.currentpage-1)*this.recordPerPage;
	}
	public int getPagecode() {
		return pagecode;
	}

	public void setPagecode(int pagecode) {
		this.pagecode = pagecode;
	}
	/**
	 * 构造函数
	 * @param recordPerPage 每页显示的记录数
	 * @param currentpage 当前页
	 */
	public PageView(int recordPerPage, int currentpage) {
		this.recordPerPage = recordPerPage;
		this.currentpage = currentpage;
	}
	/**
	 * 构造函数
	 * @param recordPerPage 每页显示的记录数
	 * @param currentpage 当前页
	 * @param pagecode 页码数量
	 */
	public PageView(int recordPerPage, int currentpage,int pagecode) {
		this.recordPerPage = recordPerPage;
		this.currentpage = currentpage;
		this.pagecode=pagecode;
	}
	
	public void setQueryResult(QueryResult<T> qr){
		setTotalrecord(qr.getTotalrecord());
		setRecords(qr.getResultlist());
	}
	
	public long getTotalrecord() {
		return totalrecord;
	}
	public void setTotalrecord(long totalrecord) {
		this.totalrecord = totalrecord;
		//总记录数变化时,要重新计算总页码和页码开始,结束索引
		setTotalpage(this.totalrecord%this.recordPerPage==0? this.totalrecord/this.recordPerPage : this.totalrecord/this.recordPerPage+1);
	}
	public List<T> getRecords() {
		return records;
	}
	public void setRecords(List<T> records) {
		this.records = records;
	}
	public PageIndex getPageindex() {
		return pageindex;
	}
	public long getTotalpage() {
		return totalpage;
	}
	public void setTotalpage(long totalpage) {
		this.totalpage = totalpage;
		this.pageindex = PageIndex.getPageIndex(pagecode, currentpage, totalpage);
	}
	public int getRecordPerPage() {
		return recordPerPage;
	}
	public int getCurrentpage() {
		return currentpage;
	}
}

其中,页码索引类如下:

package edu.njcit.action;
/**
 * 页面页码类
 * @author Administrator
 */
public class PageIndex {
	private long startindex;//开始页码
	private long endindex;//结束页码
	
	public PageIndex(long startindex, long endindex) {
		this.startindex = startindex;
		this.endindex = endindex;
	}
	public long getStartindex() {
		return startindex;
	}
	public void setStartindex(long startindex) {
		this.startindex = startindex;
	}
	public long getEndindex() {
		return endindex;
	}
	public void setEndindex(long endindex) {
		this.endindex = endindex;
	}
	/**
	 * 根据页码数量,当前页,总页数构建页码索引
	 * @param pagecode 页码数量
	 * @param currentPage 当前页
	 * @param totalpage 总页数
	 * @return
	 */
	public static PageIndex getPageIndex(long pagecode, int currentPage, long totalpage){
			long startpage = currentPage-(pagecode%2==0? pagecode/2-1 : pagecode/2);
			long endpage = currentPage+pagecode/2;
			if(startpage<1){
				startpage = 1;
				if(totalpage>=pagecode) endpage = pagecode;
				else endpage = totalpage;
			}
			if(endpage>totalpage){
				endpage = totalpage;
				if((endpage-pagecode)>0) startpage = endpage-pagecode+1;
				else startpage = 1;
			}
			return new PageIndex(startpage, endpage);		
	}
}

QueryResult是查询结果类,是对到DB中检索出来的数据的封装,可以直接放进PageView中

package edu.njcit.action;

import java.util.List;
/**
 * 查询结果
 * @author Administrator
 * @param <T>
 */
public class QueryResult<T> {
	private List<T> resultlist;
	/**
	 * 页面看到的总记录数
	 * 默认情况下=resultlist.size(),也可自行指定
	 */
	private long totalrecord;//
	
	public List<T> getResultlist() {
		return resultlist;
	}
	public void setResultlist(List<T> resultlist) {
		this.resultlist = resultlist;
	}
	public long getTotalrecord() {
		return totalrecord;
	}
	public void setTotalrecord(long totalrecord) {
		this.totalrecord = totalrecord;
	}
	public QueryResult(List<T> resultlist, long totalrecord) {
		super();
		this.resultlist = resultlist;
		this.totalrecord = totalrecord;
	}
	
}

二、下面可以把分页单独抽出为一个JSP,需要分页时,直接include即可

<%@ page language="java" pageEncoding="UTF-8"%>
<font color="black">
    当前页:第${pageView.currentpage}页 | 总记录数:${pageView.totalrecord}条 | 每页显示:${pageView.recordPerPage}条 | 总页数:${pageView.totalpage}页
</font>
<br/>
<c:forEach begin="${pageView.pageindex.startindex}" end="${pageView.pageindex.endindex}" var="wp">
    <c:if test="${pageView.currentpage==wp}"><b><font color="gray">第${wp}页</font></b></c:if>
    <c:if test="${pageView.currentpage!=wp}"><a href="javascript:topage('${wp}')" class="a03">第${wp}页</a></c:if>
</c:forEach>
这里需要一段JS代码,用于当点击第几页时更改currentPage和提交表单:

//到指定的分页页面
	function topage(page){
		var form = document.forms[0];//包含currentPage hidden框的form
		form.currentPage.value=page;
		form.submit();
	}

三、现在就可以应用封装好的分页组件了

package edu.njcit.action.paging;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import edu.njcit.action.ActionSupportBase;
import edu.njcit.action.PageView;
import edu.njcit.action.QueryResult;
import edu.njcit.entity.Student;

public class PagingAction extends ActionSupportBase {
	
	private static final long serialVersionUID = 1L;
	@Override
	public String execute() throws Exception {
		
		List<Student> list=new ArrayList<Student>();
		//模拟数据
		for (int i = 1; i <= 300; i++) {
			Student student=new Student();
			student.setId(String.valueOf(i));
			student.setBirth(new Date());
			student.setAge(i);
			student.setName((i)+""+i);
			list.add(student);
		}
		
		PageView<Student> pageView=new PageView<Student>(12,getCurrentPage());
		int start=pageView.getStartRecordIndex();
		int lenght=pageView.getRecordPerPage();
		QueryResult<Student> qr=new QueryResult<Student>(list.subList(start, start+lenght),list.size());
		pageView.setQueryResult(qr);
		request.setAttribute("pageView", pageView);
		return ActionSupport.SUCCESS;
	}
}

结果页面如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/taglib.jsp" %>
<%
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 'index.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/style.css">
    <script language="javascript" src="/js/topage.js"></script>
  </head>
  <body>
  学生如下:<br/>
<s:form action="paging" method="post">
<s:hidden name="currentPage"></s:hidden>
<table style="border:solid 1px green;">
<tr><td>学号</td><td>姓名</td><td>年龄</td><td>生日</td></tr>
<c:forEach items="${pageView.records}" var="entry">
<tr>
<td>${entry.id}</td>
<td>${entry.name}</td>
<td>${entry.age}</td>
<td><fmt:formatDate value="${entry.birth}" type="both" pattern="yyyy-MM-dd" /></td>
</tr>
</c:forEach>
</table>
</s:form>
<!-- 将分页JSP包含进来 -->
<%@ include file="/fenye.jsp" %>
  </body>
</html>
最终效果如下:



/* * @(#)PageControl.java 1.00 2004-9-22 * * Copyright 2004 2004 . All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.hexiang.utils; /** * PageControl, 分页控制, 可以判断总页数和是否有上下页. * * 2008-07-22 加入输出上下分页HTML代码功能 * * @author HX * @version 1.1 2008-9-22 */ public class PageBean { /** 每页显示记录数 */ private int pageCount; /** 是否有上一页 */ private boolean hasPrevPage; /** 记录总数 */ private int recordCount; /** 是否有下一页 */ private boolean hasNextPage; /**总页面数 */ private int totalPage; /** 当前页码数 */ private int currentPage; /** * 分页前的页面地址 */ private String pageUrl; /** * 输出分页 HTML 页面跳转代码, 分链接和静态文字两种. * 2008-07-22 * @return HTML 代码 */ public String getPageJumpLinkHtml() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf('?') == -1) { pageUrl = pageUrl + '?'; } StringBuffer buff = new StringBuffer("<span id='pageText'>"); // 上一页翻页标记 if(currentPage > 1) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage - 1) + "' title='转到第 " + (currentPage - 1) + " 页'>上一页</a> ] "); } else { buff.append("[ 上一页 ] "); } // 下一页翻页标记 if(currentPage < getTotalPage()) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage + 1)+ "' title='转到第 " + (currentPage + 1) + " 页'>下一页</a> ] "); } else { buff.append("[ 下一页 ] "); } buff.append("</span>"); return buff.toString(); } /** * 输出页码信息: 第${currentPage}页/共${totalPage}页 * @return */ public String getPageCountHtml() { return "第" + currentPage + "页/共" + getTotalPage() + "页"; } /** * 输出 JavaScript 跳转函数代码 * @return */ public String getJavaScriptJumpCode() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf("?") == -1) { pageUrl = pageUrl + '?'; } return "<script>" + "// 页面跳转函数\n" + "// 参数: 包含页码的表单元素,例如输入框,下拉框等\n" + "function jumpPage(input) {\n" + " // 页码相同就不做跳转\n" + " if(input.value == " + currentPage + ") {" + " return;\n" + " }" + " var newUrl = '" + pageUrl + "&page=' + input.value;\n" + " document.location = newUrl;\n" + " }\n" + " </script>"; } /** * 输出页面跳转的选择框和输入框. 示例输出: * <pre> 转到 <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 --> <select onchange='jumpPage(this);'> <c:forEach var="i" begin="1" end="${totalPage}"> <option value="${i}" <c:if test="${currentPage == i}"> selected </c:if> >第${i}页</option> </c:forEach> </select> 输入页码:<input type="text" value="${currentPage}" id="jumpPageBox" size="3"> <input type="button" value="跳转" onclick="jumpPage(document.getElementById('jumpPageBox'))"> </pre> * @return */ public String getPageFormJumpHtml() { String s = "转到\n" + "\t <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 -->\n" + " <select onchange='jumpPage(this);'>\n" + " \n"; for(int i = 1; i <= getTotalPage(); i++ ) { s += "<option value=" + i + "\n"; if(currentPage == i) { s+= " selected "; } s += "\t>第" + i + "页</option>\n"; } s+= " </select>\n" + " 输入页码:<input type=\"text\" value=\"" + currentPage + "\" id=\"jumpPageBox\" size=\"3\"> \n" + " <input type=\"button\" value=\"跳转\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\"> "; return s; } /** * 进行分页计算. */ private void calculate() { if (getPageCount() == 0) { setPageCount(1); } totalPage = (int) Math.ceil(1.0 * getRecordCount() / getPageCount()); // 总页面数 if (totalPage == 0) totalPage = 1; // Check current page range, 2006-08-03 if(currentPage > totalPage) { currentPage = totalPage; } // System.out.println("currentPage=" + currentPage); // System.out.println("maxPage=" + maxPage); // // Fixed logic error at 2004-09-25 hasNextPage = currentPage < totalPage; hasPrevPage = currentPage > 1; return; } /** * @return Returns the 最大页面数. */ public int getTotalPage() { calculate(); return totalPage; } /** * @param currentPage * The 最大页面数 to set. */ @SuppressWarnings("unused") private void setTotalPage(int maxPage) { this.totalPage = maxPage; } /** * 是否有上一页数据 */ public boolean hasPrevPage() { calculate(); return hasPrevPage; } /** * 是否有下一页数据 */ public boolean hasNextPage() { calculate(); return hasNextPage; } // Test public static void main(String[] args) { PageBean pc = new PageBean(); pc.setCurrentPage(2); pc.setPageCount(4); pc.setRecordCount(5); pc.setPageUrl("product/list.do"); System.out.println("当前页 " + pc.getCurrentPage()); System.out.println("有上一页 " + pc.hasPrevPage()); System.out.println("有下一页 " + pc.hasNextPage()); System.out.println("总页面数 " + pc.getTotalPage()); System.out.println("分页 HTML 代码 " + pc.getPageJumpLinkHtml()); } /** * @return Returns the 当前页码数. */ public int getCurrentPage() { return currentPage; } /** * 设置当前页码, 从 1 开始. * @param currentPage * The 当前页码数 to set. */ public void setCurrentPage(int currentPage) { if (currentPage <= 0) { currentPage = 1; } this.currentPage = currentPage; } /** * @return Returns the recordCount. */ public int getRecordCount() { return recordCount; } /** * @param recordCount * The recordCount to set. */ public void setRecordCount(int property1) { this.recordCount = property1; } /** * @return Returns the 每页显示记录数. */ public int getPageCount() { return pageCount; } /** * @param pageCount * The 每页显示记录数 to set. */ public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String value) { pageUrl = value; } }
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值