关于java分页类
//********* 主要用于jsp网站页面呈现的分页管理中,此类具有功能强大,使用方便的特点!package lauo;
import java.util.*;
/*
*一个分页管理器,
*用于处理在网页分页系统中出现的问题
*/
public class PageManage
{
private Object[] data=null; //要管理的分页数据,这些数据存放于数组当中(条目数组)
private int perLen=1;//每页的内容长度(条目数)
private int ptr = 0; //当前指针(页码下标)
private int max = 0;//最大的页数
public PageManage(){};
/*
*设置页长
*/
public int setPerLen(int i)
{
int r = perLen;
perLen = i;
if(perLen<=0) perLen=1;
return r;
}
/*
*获得单位页所能保存的内容数(条目数)
*/
public int getPerLen()
{
perLen = perLen<=0? 1:perLen;
return perLen;
}
/*
*获得最大的页数
*/
public int getMaxPage()
{
if(data==null) return max=1;
perLen = perLen<=0?1:perLen;
return max=(data.length+perLen)/perLen;
}
/*
*下一页,得到的是++ptr
*/
public int nextPage()
{
++ptr;
ptr = ptr >= max ? max-1:ptr;
return ptr;
}
/*
*上一页
*/
public int prePage()
{
--ptr;
ptr = ptr <0 ? 0:ptr;
return ptr;
}
/*
*得到当前页码
*/
public int getPageNo()
{
int m = getMaxPage();
ptr = ptr<0?0:(ptr>m?m:ptr);
return ptr;
}
/*
*设置当前页码
*/
public int setPageNo(int i)
{
int r = ptr;
ptr = i;
ptr = ptr>=getMaxPage()?max-1:( ptr<0? 0 : ptr );
return r;
}
/*
*设置需要分页的数据
*/
public Object[] setData(Object[] d)
{
Object[] r = data;
data = d;
getMaxPage();//最大的页数
return r;
}
/*
*获得当前页,得到的是数据内容(当前页的条目数组)
*/
public Object[] getNowPage()
{
getPerLen();
Object[] page = new Object[perLen];
for(int i=0;i<perLen &&data!=null &&i+ptr*perLen<data.length;i++)
page[i]=data[ptr*perLen+i];
return page;
}
/*
*得到数据所在页范围的条目数据下界
*/
public int getNowPageLow()
{
getPerLen();
getPageNo();
return ptr*perLen;//下界
}
/*
*获得所在页范围的条目数据上界
*/
public int getNowPageHigh()
{
try{
getPerLen();
getPageNo();
int h=ptr*perLen+perLen-1;//上界
h = h>=data.length?data.length-1:h;
return h;
}
catch(Exception e){ return 0;}
}
/*
*获得某一区间内的页码
*包括首未页,返回的是页码
*int range;为页码呈现的区间。如 【3】 【4】 【5】 这个区间长度为3
*/
public int[] getRange(int range)
{
getPageNo();
int[] ans = null;
int m =getMaxPage();//得到最大的页码
range = range<=0?1:(range>m?m:range);
ans = new int[range];//得到区间页码存储数组
int left = ptr - range/2 ; //得到最左侧的页码
left = left <0?0:(left+range>=m ? m-range:left); //游动、修正
for(int i=0;i<range;i++,left++)
ans[i]=left;//得到页标范围的结果
return ans;
}
}
使用举例(jsp 源码摘要):
<jsp:useBean id="pager" class="lauo.PageManage" scope="session"></jsp:useBean><!---使用分页管理器 javaBeans --->
String pnoStr = request.getParameter("pageNo");
Integer pno = pnoStr==null?0:Integer.parseInt(pnoStr);
pager.setPageNo(pno.intValue());
pager.setPerLen(30);
Vector<Object[]> v = bbsDbm.getBoardArticles(bname);//获得对应版面的文章列表
Object[] pat=null;
pat = v==null||v.size()==0?null:new Object[v.size()];
pager.setData(pat);//设置数据
int i=0,j=pager.getNowPageLow(),len=pager.getPerLen(),
high=pager.getNowPageHigh(),vsize=v.size();
int []range = pager.getRange(10);//获得页码呈现的区间
if(pager.getMaxPage()>1)//要呈现的页面超过1页,需要分页呈现
{
wstr+=("<tr><th align='center'><font color='blue'>");
wstr+=("<a href='board.jsp?pageNo=0'>[首页]</a> ");
for(i=0;i<range.length;i++)
wstr+=("<a href='board.jsp?pageNo="+range[i]+"'>["+(range[i]+1)+"]</a> ");
wstr+=("<a href='board.jsp?pageNo="+(pager.getMaxPage()-1)+"'>[末页]</a> ");
wstr+=("</th></tr>");
}
--------------------编程问答-------------------- --------------------编程问答-------------------- 额,分享贴呢,顶一下! --------------------编程问答-------------------- 我怎么看着,写的很乱啊, --------------------编程问答-------------------- 分页工具类:PageUtil.java
/**
* @Title: PageUtil.java
* @Package commons.pagination
* @Description: 分页工具类
* @author zwzheng
* @date Oct 22, 2012 10:15:05 AM
* @version V1.0
*/
package com.guanri.core.commons.pagination;
/**
* @ClassName: PageUtil
* @Description: 分页工具类
* @author zwzheng
* @date Oct 22, 2012 10:15:05 AM
*/
public class PageUtil {
/**
* 当前页码
*/
private int pageNo = 1;
/**
* 每页显示多少页
*/
private int pageSize = 10;
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
--------------------编程问答-------------------- 分页工具支持类:PageSupport.java
/**
* @Title: PaginationSupport.java
* @Package commons.pagination
* @Description: TODO(用一句话描述该文件做什么)
* @author zwzheng
* @date Oct 22, 2012 10:14:51 AM
* @version V1.0
*/
package com.guanri.core.commons.pagination;
/**
* @ClassName: PaginationSupport
* @Description: 分页工具类
* @author zwzheng
* @date Oct 22, 2012 10:14:51 AM
*/
public class PageSupport {
/**
* 默认每页显示多少页
*/
private static int DEFAULT_PAGE_SIZE = 10;
/**
* 每页记录页数
*/
private int pageSize = DEFAULT_PAGE_SIZE;
/**
* 当前页中存放的记录,类型一般为List
*/
private Object data;
/**
* 总页数
*/
private int pageCount;
/**
* 总记录数
*/
private int rowCount;
/**
* 跳转页数
*/
private int pageNo;
/**
* 构造方法,
*/
public PageSupport(int pageNo, int rowCount) {
this.pageNo = pageNo;
this.rowCount = rowCount;
this.pageCount = getTotalPageCount();
}
/**
* 构造方法,
*/
public PageSupport(int pageNo, int pageSize, int rowCount) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.rowCount = rowCount;
this.pageCount = getTotalPageCount();
}
/**
* 构造方法,构造所有
*/
public PageSupport(int pageNo, int pageSize, int rowCount, Object data) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.rowCount = rowCount;
this.pageCount = getTotalPageCount();
this.data = data;
}
/**
* @Title: getTotalPageCount
* @Description: 获取总页数
* @param
* @return 设定文件
* @return int 返回类型
* @throws
*/
private final int getTotalPageCount() {
if (rowCount % pageSize == 0)
return rowCount / pageSize;
else
return rowCount / pageSize + 1;
}
/**
* @Title: getStartOfPage
* @Description: 获取跳转页第一条数据在数据集的位置.
* @param
* @return 设定文件
* @return int 返回类型
* @throws
*/
public int getStartOfPage() {
return (pageNo - 1) * pageSize;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
}
--------------------编程问答-------------------- --------------------编程问答-------------------- 我已一个查询用户列表的例子作说明:我是基于pager-taglib-2.0.jar来分页,其分页效果类似google和百度的分页 --------------------编程问答-------------------- page.jsp:该页面是一个公共的分页标签
<%@ page contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript">
var totalRows=${pageSupport.rowCount};
var pageSize=${pageSupport.pageSize};
//alert(${currentPageNumber});
function queryPage(){
var toPage=document.getElementById("pageUtil.pageNo").value;
//var pager.offset
//(pageNo - 1) * pageSize;
//var offset = toPage*pageSize-3;
var offset = (toPage-1)*pageSize;
if(isNaN(toPage)){
alert("不是数字,请输入正整数.");
return;
}
if(toPage <= 0){
toPage=1;
}
//校验是跳转页是否在记录有效范围内
//取大于等于总页数的值
var totalPage=Math.ceil(totalRows/pageSize);
if(toPage>totalPage){
toPage=totalPage;
}
document.getElementById("pageUtil.pageNo").value=toPage;
var arr = document.forms[0].elements;
var flag = false;
for(var i=0,j=arr.length;i<j;i++){
if(arr[i].getAttribute("name")=="pageUtil.pageNo"){
flag = true;
break;
}
}
if(!flag){
var artionUrl = document.forms[0].getAttribute("action");
artionUrl = artionUrl + "?pager.offset="+offset+"&pageUtil.pageNo="+toPage;
document.forms[0].setAttribute("action",artionUrl);
}
//alert(document.forms[0].getAttribute("action"));
document.forms[0].submit();
}
</script>
总计${pageSupport.rowCount}条记录 共${pageSupport.pageCount}页 每页${pageSupport.pageSize}条
<pg:first>
<a href="${pageUrl}&pageUtil.pageNo=${pageNumber }"> <img
src="images/firstPage.gif" border="0" title="首页"> </a>
</pg:first>
<pg:prev>
<a href="${pageUrl }&pageUtil.pageNo=${pageNumber }"> <img
src="images/prevPage.gif" border="0" title="上一页"> </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 }&pageUtil.pageNo=${pageNumber }">${pageNumber}</a>
</c:otherwise>
</c:choose>
</pg:pages>
<pg:next>
<a href="${pageUrl }&pageUtil.pageNo=${pageNumber }"> <img
src="images/nextPage.gif" border="0" title="下一页"> </a>
</pg:next>
<pg:last>
<a href="${pageUrl }&pageUtil.pageNo=${pageNumber }"> <img
src="images/lastPage.gif" border="0" title="尾页"> </a>
</pg:last>
第
<input id="pageUtil.pageNo" name="pageUtil.pageNo" type="text"
maxlength="6" value="${pageUtil.pageNo}" size="3"
onkeyup="value=value.replace(/[^\d]/g,'')" />
<input name="bj" id="bj" type="button" value="GO" class="button"
onClick="queryPage(0);" />
--------------------编程问答-------------------- userList.jsp:该页面是用户列表展示页面,请看地步,引用了page.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:directive.include file="/WEB-INF/tag.inc" />
<%@ include file="/jsp/common/tags.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>users</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="styles.css">
-->
<style rel="stylesheet" type="text/css">
</style>
<script type="text/javascript">
j(function(){
/**导出pdf*/
j("#pdfBtn").click(function (){
action = j("#userinfoListForm").attr("action");
j("#userinfoListForm").attr("action","${ctx}/userInfoManage/userInfoAction!export.action?exportType=pdf");
j("#userinfoListForm").submit();
j("#userinfoListForm").attr("action",action);
});
/**导出exl*/
j("#xlsBtn").click(function (){
action = j("#userinfoListForm").attr("action");
j("#userinfoListForm").attr("action","${ctx}/userInfoManage/userInfoAction!export.action?exportType=xls");
j("#userinfoListForm").submit();
j("#userinfoListForm").attr("action",action);
});
/**表单重置:只能达到还原的作用*/
j("#btnRes").click(function (){
j("#userinfoListForm")[0].reset();
});
});
</script>
</head>
<body>
<div id="man_zone">
<table border="0" cellpadding="0" cellspacing="0"
class="div_subtitle">
<tr>
<td id="titleDiv">
当前位置>>用户管理>>查询用户
</td>
</tr>
</table>
<form action="${ctx}/userInfoManage/sysUserinfoAction!list.action"
method="post" id="userinfoListForm">
<table id="search" cellspacing="0" cellpadding="2">
<tr>
<td class="left" width="20%">
用户编号:
</td>
<td class="right">
<input type="text" name="sysUserinfo.userId" id="userId"
class="input" value="${sysUserinfo.userId}" />
</td>
<td class="left" width="20%">
用户名称:
</td>
<td class="right">
<input type="text" name="sysUserinfo.userName" id="userName"
class="input" value="${sysUserinfo.userName}" />
</td>
</tr>
<tr>
<td class="left" width="20%">
用户状态:
</td>
<td class="right">
<select name="sysUserinfo.userState" id="userState"
style="width: 160px">
<option value="" />
<c:forEach items="${userStateFun:all_userState()}" var="entry">
<option value="${entry.key}"
<c:if test="${sysUserinfo.userState==entry.key }">selected="selected"</c:if>>
<c:out value="${entry.value}" />
</option>
</c:forEach>
<lect>
</td>
<td class="left" width="20%">
注册时间:
</td>
<td class="right">
<input type="text" id="startdate" name="startDate"
style="width: 73px" value="${startDate }"
onfocus="WdatePicker({lang:'${sessionScope.lang }',dateFmt:'yyyy-MM-dd',maxDate:'#F{$dp.$D(\'endDate\',{d:0})}'})"
readonly="readonly" />
-
<input type="text" id="endDate" name="endDate"
style="width: 73px" value="${endDate }"
onfocus="WdatePicker({lang:'${sessionScope.lang }',dateFmt:'yyyy-MM-dd',minDate:'#F{$dp.$D(\'startdate\',{d:0})}'})"
readonly="readonly" />
</td>
</tr>
<tr>
<td align="center" colspan="4">
<input type="submit" name="btnSub" id="btnSub" value="查询"
class="button" />
<input type="button" name="btnRes" id="btnRes" value="重置"
class="button" />
<input type="button" id="pdfBtn" value="导出PDF" class="button" />
<input type="button" id="xlsBtn" value="导出XLS" class="button" />
</td>
</tr>
</table>
</form>
<table class="list" cellspacing="0" cellpadding="1">
<tr align="center">
<th style="width: 20%;">
用户编号
</th>
<th style="width: 20%;">
用户名称
</th>
<th style="width: 20%;">
用户状态
</th>
<th style="width: 20%;">
创建时间
</th>
<th style="width: 20%;">
操作
</th>
</tr>
<c:choose>
<c:when test="${empty pageSupport.data}">
<tr>
<td colspan="5">
<font color="red">没有记录!</font>
</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach var="item" items="${pageSupport.data}" varStatus="vs">
<tr>
<td>
${item.userId}
</td>
<td>
${item.userName}
</td>
<td>
${userStateFun:userStateCN(item.userState)}
</td>
<td>
<fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd" />
</td>
<td>
<a href="#">编辑</a>
<a
href="${ctx}/userInfoManage/sysUserinfoAction!getSysUserinfoByUserId.action?userId=${item.userId }">明细</a>
<a
href="${ctx}/userInfoManage/sysUserinfoAction!toAssignSysUserRoleInfo.action?userId=${item.userId }">分配角色</a>
<a href="#">禁用</a>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
<br/>
<c:if test="${not empty pageSupport.data}">
<table width="100%" border="0" align="center" cellpadding="0"
cellspacing="0" class="paeg_bar">
<tr>
<td height="30" width="100%" align="right">
<pg:pager url="sysUserinfoManage/sysUserinfoAction!list.action"
items="${pageSupport.rowCount}" index="center"
maxPageItems="${pageUtil.pageSize}" maxIndexPages="5"
isOffset="<%=false%>"
export="pageOffset,currentPageNumber=pageNumber" scope="request">
<pg:param name="sysUserinfo.userId" value="${sysUserinfo.userId}" />
<pg:param name="sysUserinfo.userName" value="${sysUserinfo.userName}" />
<pg:param name="sysUserinfo.userState"
value="${sysUserinfo.userState}" />
<pg:param name="startDate" value="${startDate}" />
<pg:param name="endDate" value="${endDate}" />
<pg:index>
<c:import url="/jsp/common/page.jsp"></c:import>
</pg:index>
</pg:pager>
</td>
</tr>
</table>
</c:if>
</body>
</html> --------------------编程问答-------------------- 分页搞个JQ插件也可以啊 --------------------编程问答-------------------- Action:SysUserinfoAction.java,我就只写一个加载用户列表的方法
@SuppressWarnings("unchecked")
@Controller("sysUserinfoAction")
public class SysUserinfoAction extends BaseAction {
/**
* Logger for this class
*/
private static final Logger logger = Logger
.getLogger(SysUserinfoAction.class);
/**
* 注入区
*/
@Resource
private ISysUserinfoService sysUserinfoService;
/**
* 属性定义区
*/
private SysUserinfo sysUserinfo;
private String userId;
/**
* 起止日期
*/
private String startDate;
private String endDate;
// 分页工具
private PageSupport pageSupport;
private PageUtil pageUtil;
/**
* @Title: list
* @Description: 分页查询用户信息
* @param
* @return
* @param
* @throws Exception
* 设定文件
* @return String 返回类型
* @throws
*/
public String list() throws Exception {
pageUtil = pageUtil != null ? pageUtil : new PageUtil();
sysUserinfo = sysUserinfo != null ? sysUserinfo : new SysUserinfo();
pageSupport = sysUserinfoService.findSysUserinfoPageSupport(
sysUserinfo, startDate, endDate, pageUtil);
// 记录日志表
return "list";
}
}
--------------------编程问答-------------------- server接口ISysUserinfoService.java和实现类SysUserinfoServiceImpl.java
ISysUserinfoService.java
public interface ISysUserinfoService {
/**
* @Title: findUserInfoPageSupport
* @Description: 分页查询用户列表信息
* @param
* @param userInfo
* 用戶信息
* @param
* @param pageUtil
* 分頁工具
* @param
* @return 设定文件
* @return PageSupport 返回类型 分頁工具
* @throws
*/
public PageSupport findSysUserinfoPageSupport(SysUserinfo sysUserinfo,
String startDate, String endDate, PageUtil pageUtil);
}
SysUserinfoServiceImpl.java
@SuppressWarnings("unchecked")
@Service("sysUserinfoService")
public class SysUserinfoServiceImpl implements ISysUserinfoService {
/**
* logger for UserInfoServiceImpl Class
*/
private static final Logger logger = Logger
.getLogger(SysUserinfoServiceImpl.class);
/**
* 注入区
*/
@Resource
private ISysUserinfoDao sysUserinfoDao;
/**
* @Title: findUserInfoPageSupport
* @Description: 分页查询用户列表信息
* @param
* @param userInfo
* 用戶信息
* @param
* @param pageUtil
* 分頁工具
* @param
* @return 设定文件
* @return PageSupport 返回类型 分頁工具
* @throws
*/
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
public PageSupport findSysUserinfoPageSupport(SysUserinfo sysUserinfo,
String startDate, String endDate, PageUtil pageUtil) {
return sysUserinfoDao.findSysUserinfoPageSupport(sysUserinfo,
startDate, endDate, pageUtil);
}
}
--------------------编程问答-------------------- DAO层接口ISysUserinfoDao .java和DAO实现类SysUserinfoDaoImpl.java
ISysUserinfoDao .java
/**
* @ClassName: ISysUserinfoDao
* @Description: 用户DAO
* @author zwzheng
* @date Oct 22, 2012 12:36:51 PM
*/
public interface ISysUserinfoDao extends IBaseHibernateDao {
/**
* @Title: findUserInfoPageSupport
* @Description: 分页查询用户列表信息
* @param
* @param userInfo
* 用戶信息
* @param
* @param pageUtil
* 分頁工具
* @param
* @return 设定文件
* @return PageSupport 返回类型 分頁工具
* @throws
*/
public PageSupport findSysUserinfoPageSupport(SysUserinfo sysUserinfo,
String startDate, String endDate, PageUtil pageUtil);
}
SysUserinfoDaoImpl.java
@SuppressWarnings("unchecked")
@Repository("sysUserinfoDao")
public class SysUserinfoDaoImpl extends BaseHibernateDaoImpl implements
ISysUserinfoDao {
/**
* @Title: findUserInfoPageSupport
* @Description: 分页查询用户列表信息
* @param
* @param userInfo
* 用戶信息
* @param
* @param pageUtil
* 分頁工具
* @param
* @return 设定文件
* @return PageSupport 返回类型 分頁工具
* @throws
*/
public PageSupport findSysUserinfoPageSupport(SysUserinfo sysUserinfo,
String startDate, String endDate, PageUtil pageUtil) {
Criteria criteria = super.createCriteria();
if (sysUserinfo != null) {
// if (StringUtils.isNotEmpty(userInfo.getUserName())) {
// criteria.add(Restrictions.like("userName", userInfo
// .getUserName().trim(), MatchMode.ANYWHERE));
// }
// if (StringUtils.isNotEmpty(userInfo.getUserState())) {
// criteria.add(Restrictions.eq("userState", userInfo
// .getUserState().trim()));
// }
if (StringUtils.isNotEmpty(startDate)
&& StringUtils.isNotEmpty(endDate)) {
criteria.add(Restrictions.between("createTime", DateUtils
.parseDateFromPattern(startDate,
DateUtils.defaultDatePattern), DateUtils
.parseDateFromPattern(endDate,
DateUtils.defaultDatePattern)));
}
}
// 获取记录总数
Integer rowCount = super.getTotalByCriteria(criteria);
// 增加排序字段
criteria.addOrder(Order.desc("userId"));
return super.findListByPageSupport(criteria, pageUtil.getPageNo(),
pageUtil.getPageSize(), rowCount);
}
} --------------------编程问答-------------------- --------------------编程问答--------------------
咋都不排一下版啊, 看着都晕了。
补充:Java , Java EE