发表一个自己常用的分页的通用代码,实现了ajax分页。此例子是在Struts2+Hibernate+Spring框架下实现的,分页工具类是通用的,只不过查询、控制是根据使用的方法的不同而不同。
?
PaginationUtil.java
package com.dsh.pagination.tool;
/**
* ajax分页
* @author: DuanLang
* @company:oddTech
* @time:2011-12-2 上午11:10:36
*/
public class PaginationUtil {
/** 设置当前页码 */
private int curPage = 1;
/** 设置每一页的行数 */
private int pageSize = 15;
/** 从数据库读取的开始记录数 */
private int start;
/** 从数据库读取的行数(每一页显示的记录数) */
private int pageCount;
/** 总共行数(记录数) */
private int totalRow;
/** 总共页数 */
private int totalPage;
/** 分页导航条 */
private String pageBar;
/**
*
* 根据从数据库读出的总记录数初始化相应的分页变量
*
* @param totalRow
* 总记录数
*/
public void setPagesVariable(int totalRow) {
this.setTotalRow(totalRow);
this.setTotalPage(totalRow / pageSize);
if (totalRow % pageSize > 0) {
this.setTotalPage(totalPage + 1);
}
if (curPage > 1) {
this.setStart((curPage - 1) * pageSize);
} else {
this.setStart(0);
}
this.setPageCount(pageSize);
}
/**
*
* @return the curPage
*/
public int getCurPage() {
return curPage;
}
/**
*
* @param curPage
*
* the curPage to set
*/
public void setCurPage(int curPage) {
this.curPage = curPage;
}
/**
*
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
*
* @param pageSize
*
* the pageSize to set
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
*
* @return the start
*/
public int getStart() {
return start;
}
/**
*
* @param start
*
* the start to set
*/
public void setStart(int start) {
this.start = start;
}
/**
*
* @return the pageCount
*/
public int getPageCount() {
return pageCount;
}
/**
*
* @param pageCount
* the pageCount to set
*/
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
/**
*
* @return the totalRow
*/
public int getTotalRow() {
return totalRow;
}
/**
*
* @param totalRow
*
* the totalRow to set
*/
public void setTotalRow(int totalRow) {
this.totalRow = totalRow;
}
/**
*
* @return the totalPage
*/
public int getTotalPage() {
return totalPage;
}
/**
*
* @param totalPage
*
* the totalPage to set
*/
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
/**
*
* @return the pageBar
*/
public String getPageBar() {
return pageBar;
}
/**
*
* @param pageBar
*
* the pageBar to set
*/
public void setPageBar(String pageBar) {
this.pageBar = pageBar;
}
/**
*
* 分页导航条(显示分页链接控制代码)
*
* @return
*/
public String getToolsMenu() {
StringBuffer str = new StringBuffer("");
int next, prev;
prev = curPage - 1;
next = curPage + 1;
if (curPage > 1) {
str.append("<a href=\"#\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value=1;this.parentNode.submit();\">首页</a>&nbsp;");
} else {
str.append("首页&nbsp;");
}
if (curPage > 1) {
str.append("<a href=\"#\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ prev + ";this.parentNode.submit();\">上页</a>&nbsp;");
} else {
str.append("上页</a>&nbsp;");
}
if (curPage < totalPage) {
str.append("<a href=\"#\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ next + ";this.parentNode.submit();\">下页</a>&nbsp;");
} else {
str.append("下页&nbsp;");
}
if (totalPage > 1 && curPage != totalPage) {
str.append("<a href=\"#\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ totalPage
+ ";this.parentNode.submit();\">末页</a>&nbsp;&nbsp;");
} else {
str.append("末页&nbsp;&nbsp;");
}
str.append(" 共" + totalRow + "条记录");
str.append(" 每页<SELECT size=\"1\" name=\"page.pageSize\" onchange=\"this.form.getElementsByTagName('input')[0].value=1;this.form.submit();\">");
if (pageSize == 2) {
str.append("<OPTION value=2 selected>2</OPTION>");
} else {
str.append("<OPTION value=2>2</OPTION>");
}
if (pageSize == 5) {
str.append("<OPTION value=5 selected>5</OPTION>");
} else {
str.append("<OPTION value=5>5</OPTION>");
}
if (pageSize == 10) {
str.append("<OPTION value=10 selected>10</OPTION>");
} else {
str.append("<OPTION value=10>10</OPTION>");
}
if (pageSize == 15) {
str.append("<OPTION value=15 selected>15</OPTION>");
} else {
str.append("<OPTION value=15>15</OPTION>");
}
if (pageSize == 20) {
str.append("<OPTION value=20 selected>20</OPTION>");
} else {
str.append("<OPTION value=20>20</OPTION>");
}
if (pageSize == 50) {
str.append("<OPTION value=50 selected>50</OPTION>");
} else {
str.append("<OPTION value=50>50</OPTION>");
}
if (pageSize == 100) {
str.append("<OPTION value=100 selected>100</OPTION>");
} else {
str.append("<OPTION value=100>100</OPTION>");
}
str.append("</SELECT>");
str.append("条 分" + totalPage + "页显示 转到");
str.append("<SELECT size=\"1\" name=\"Pagelist\" onchange=\"this.form.getElementsByTagName('input')[0].value=this.value;this.form.submit();\">");
for (int i = 1; i < totalPage + 1; i++) {
if (i == curPage) {
str.append("<OPTION value=" + i + " selected>" + i
+ "</OPTION>");
} else {
str.append("<OPTION value=" + i + ">" + i + "</OPTION>");
}
}
str.append("</SELECT>页");
str.append("<INPUT type=\"hidden\" value=" + curPage
+ " name=\"page.curPage\" > ");
return str.toString();
}
/**
*
* AJAX分页导航条(显示分页链接控制代码)
*
* @return
*/
public String getAJAXToolsMenu() {
StringBuffer str = new StringBuffer("");
int next, prev;
prev = curPage - 1;
next = curPage + 1;
str.append("<span class=\"showControlPage\">");
if (curPage > 1) {
str.append("<a href=\"javascript:\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value=1;showPages(this.parentNode.getElementsByTagName('input')[0].value,this.parentNode.getElementsByTagName('select')[0].value);\">首页</a>&nbsp;");
} else {
str.append("首页&nbsp;");
}
if (curPage > 1) {
str.append("<a href=\"javascript:\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ prev
+ ";showPages(this.parentNode.getElementsByTagName('input')[0].value,this.parentNode.getElementsByTagName('select')[0].value);\">上页</a>&nbsp;");
} else {
str.append("上页</a>&nbsp;");
}
if (curPage < totalPage) {
str.append("<a href=\"javascript:\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ next
+ ";showPages(this.parentNode.getElementsByTagName('input')[0].value,this.parentNode.getElementsByTagName('select')[0].value);\">下页</a>&nbsp;");
} else {
str.append("下页&nbsp;");
}
if (totalPage > 1 && curPage != totalPage) {
str.append("<a href=\"javascript:\" onclick=\"this.parentNode.getElementsByTagName('input')[0].value="
+ totalPage
+ ";showPages(this.parentNode.getElementsByTagName('input')[0].value,this.parentNode.getElementsByTagName('select')[0].value);\">末页</a>&nbsp;&nbsp;");
} else {
str.append("末页&nbsp;&nbsp;");
}
str.append(" 共" + totalRow + "条记录");
str.append(" 每页<SELECT size=\"1\" name=\"page.pageSize\" onchange=\"this.parentNode.getElementsByTagName('input')[0].value=1;showPages(1,this.value);\">");
if (pageSize == 2) {
str.append("<OPTION value=2 selected>2</OPTION>");
} else {
str.append("<OPTION value=2>2</OPTION>");
}
if (pageSize == 5) {
str.append("<OPTION value=5 selected>5</OPTION>");
} else {
str.append("<OPTION value=5>5</OPTION>");
}
if (pageSize == 10) {
str.append("<OPTION value=10 selected>10</OPTION>");
} else {
str.append("<OPTION value=10>10</OPTION>");
}
if (pageSize == 15) {
str.append("<OPTION value=15 selected>15</OPTION>");
} else {
str.append("<OPTION value=15>15</OPTION>");
}
if (pageSize == 20) {
str.append("<OPTION value=20 selected>20</OPTION>");
} else {
str.append("<OPTION value=20>20</OPTION>");
}
if (pageSize == 50) {
str.append("<OPTION value=50 selected>50</OPTION>");
} else {
str.append("<OPTION value=50>50</OPTION>");
}
if (pageSize == 100) {
str.append("<OPTION value=100 selected>100</OPTION>");
} else {
str.append("<OPTION value=100>100</OPTION>");
}
str.append("</SELECT>");
str.append("条 分" + totalPage + "页显示 转到");
str.append("<SELECT size=\"1\" name=\"Pagelist\" onchange=\"this.parentNode.getElementsByTagName('input')[0].value=this.value;showPages(this.value,this.parentNode.getElementsByTagName('select')[0].value);\">");
for (int i = 1; i < totalPage + 1; i++) {
if (i == curPage) {
str.append("<OPTION value=" + i + " selected>" + i
+ "</OPTION>");
} else {
str.append("<OPTION value=" + i + ">" + i + "</OPTION>");
}
}
str.append("</SELECT>页");
str.append("<INPUT type=\"hidden\" value=" + curPage
+ " name=\"page.curPage\" > ");
str.append("</span>");
return str.toString();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PageUtil [curPage=" + curPage + ", pageSize=" + pageSize
+ ", start=" + start + ", pageCount=" + pageCount
+ ", totalRow=" + totalRow + ", totalPage=" + totalPage + "]";
}
}
?这个是实现根据分页的信息(查询起始标号、要查询的记录的条数)来从数据库中读取信息。
UserDaoImpl.java
package com.dsh.pagination.dao.impl;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.dsh.pagination.dao.UserDao;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public List getUserByPageInfo(Map<String, Integer> pageMap) {
Query query=this.getSession().createQuery("from User");
query.setFirstResult(pageMap.get("start"));//设置数据查询的开始位置
query.setMaxResults(pageMap.get("pageCount")); //设置查询的条数
return query.list();
}
@Override
public int getAllUserNum() {
Query query=this.getSession().createQuery("select count(u.id) as number from User u");
int num=((Number)query.iterate().next()).intValue();
return num;
}
}
?Service层就不贴出来了,基本上和Dao层差不多。下面贴出控制层代码,负责从前台获取分页的信息,和向前台发送从数据库中查询出的信息,传送是以json格式进行的。
?
UserActionImpl.java
package com.dsh.pagination.action.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.json.annotations.JSON;
import com.dsh.pagination.action.UserAction;
import com.dsh.pagination.model.User;
import com.dsh.pagination.service.UserService;
import com.dsh.pagination.tool.JsonUtil;
import com.dsh.pagination.tool.PaginationUtil;
import com.opensymphony.xwork2.ActionSupport;
public class UserActionImpl extends ActionSupport implements UserAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private UserService us;
private List<User> list;
private PaginationUtil pageUtil;
private String pageBar;
private String users;
@Override
public String getUserByPageInfo() {
System.out.println(pageUtil.getPageSize()+"从前台获取的数据");
int num = this.us.getUserNum();
System.out.println(num+"这是数据库中用户的个数");
pageUtil.setPagesVariable(num);
this.pageBar = pageUtil.getAJAXToolsMenu();
Map<String, Integer> pageInfo = new HashMap<String, Integer>();
pageInfo.put("start", pageUtil.getStart());// 设置数据查询的开始位置
pageInfo.put("pageCount", pageUtil.getPageCount());// 设置查询的数据条数
list = us.getUserByPageInfo(pageInfo);// 去业务层获取数据
if (list.size() > 0) {
this.users=JsonUtil.listToJson(list);
return SUCCESS;
}
return ERROR;
}
@JSON(serialize=false)
public UserService getUs() {
return us;
}
public void setUs(UserService us) {
this.us = us;
}
@JSON(serialize=false)
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
@JSON(serialize=false)
public PaginationUtil getPageUtil() {
return pageUtil;
}
public void setPageUtil(PaginationUtil pageUtil) {
this.pageUtil = pageUtil;
}
@JSON(name="pageBar")
public String getPageBar() {
return pageBar;
}
public void setPageBar(String pageBar) {
this.pageBar = pageBar;
}
@JSON(name="users")
public String getUsers() {
return users;
}
public void setUsers(String users) {
this.users = users;
}
}
?在前台我们就可以通过如下的方式进行调用了
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>java通用分页显示数据</title>
<script type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript">
var curPage = 1, pageSize = 10;
$(function() {
dataInfoList();
});
function dataInfoList() {
submitData = "pageUtil.curPage=" + curPage + "&pageUtil.pageSize=" + pageSize;
$.ajax({ //一个Ajax过程
type : "post", //以post方式与后台沟通
url : "getUserByPageInfoAction.action", //与此页面沟通
dataType : "json",//返回的值以 html方式 解释
data :submitData,
beforeSend : function(XMLHttpRequest) {
$("#loadingMessage")
.html(
"&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"/html/images/loading.gif\"><span>请稍后,数据加载中!</span>");
$("#loadingMessage").css({
display : ""
});
},
success : function(data) {//如果调用成功
var users=eval('('+data.users+')');
alert(users[0].id);
/* for(i in users){
$("#site_list").html(user[i].id);
} */
$("#loadingMessage").css({
display : "none"
});
$("#pageBar").html(data.pageBar);
},
error : function() {
$("#loadingMessage").css({
display : ""
});
$("#loadingMessage")
.html(
"<span class=\"errorFont\">数据加载遇到错误,请稍后再试</span>");
}
});
}
function showPages(curPageUser, pageSizeUser) {
curPage = curPageUser;
pageSize = pageSizeUser;
dataInfoList();
}
</script>
</head>
<body>
<div id="site_list">
</div>
<div class="showControlPage"></div>
<div id="loadingMessage"></div>
<div id="pageBar"></div>
</body>
</html>
?简单的效果如下所示,我的数据库中并没用任何数据,所以效果只能显示成这样了。
?
?
<span style="font-family: Simsun; font-size: medium;">首页?上页?
下页?
末页?? 共20条记录 每页<select name="page.pageSize" size="1"><option value="2">2</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option></select>条 分2页显示 转到<select name="Pagelist" size="1"><option value="1">1</option>
<option value="2">2</option></select>页</span>
?