分页问题一直是项目中不可避免的问题,之前由于一直忙着做项目,里面的分页觉得做的不是很完善,很多的代码需要复制粘帖,特别是在jsp页面上显示的时候,所以花了几天时间好好完善下!
1、封装分页信息的bean
- package com.beckham.page;
- import java.util.List;
- /**
- * @author beckham
- * Jul 30, 2009 4:13:43 PM
- * 分页信息
- */
- public class PageBean {
- private int totalSize; // 记录总条数
- private int pageSize; // 每页显示条数
- private int prePage; // 上一页
- private int nextPage; // 下一页
- private int currPage; // 当前页
- private int lastPage; // 最后页
- private int pageCount; // 总页数
- private int beginIndex ;
- private int endIndex ;
- public int getBeginIndex() {
- return beginIndex;
- }
- public void setBeginIndex(int beginIndex) {
- this.beginIndex = beginIndex;
- }
- public int getEndIndex() {
- return endIndex;
- }
- public void setEndIndex(int endIndex) {
- this.endIndex = endIndex;
- }
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public int getPrePage() {
- return prePage;
- }
- public void setPrePage(int prePage) {
- this.prePage = prePage;
- }
- public int getNextPage() {
- return nextPage;
- }
- public void setNextPage(int nextPage) {
- this.nextPage = nextPage;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- public int getLastPage() {
- return lastPage;
- }
- public void setLastPage(int lastPage) {
- this.lastPage = lastPage;
- }
- public int getPageCount() {
- return pageCount;
- }
- public void setPageCount(int pageCount) {
- this.pageCount = pageCount;
- }
- }
2、通过 传递的参数来计算分页信息,参数主要有 当前页(currPage)、结果集的总条数(totalSize)、每页显示的数量(pageSize),我把pageSize写在了配置文件里面,这样可以灵活的修改配置。
- package com.beckham.page;
- import com.beckham.util.PropertyUtil;
- public class PageMessage {
- /*
- * (non-Javadoc)
- * 获取分页信息
- * @see com.beckham.page.PageMessageInterface#getPageMessage(int,
- * java.lang.String)
- */
- public static PageBean getPageMessage(int currPage, int totalSize)
- throws Exception {
- PageBean pagebean = new PageBean();
- int pageSize = PropertyUtil.getPageSize();
- int pageCount = 0;
- int prePage = 0;
- int nextPage = 0;
- int begindex;
- int endindex;
- // 总页数
- if (totalSize % pageSize == 0) { // 判断是否整除
- pageCount = (int) totalSize / pageSize;
- } else {
- pageCount = (int) totalSize / pageSize + 1;
- }
- if (currPage > 1) {
- prePage = currPage - 1; // 上一页
- } else {
- prePage = 1;
- }
- if (currPage < pageCount) {
- nextPage = currPage + 1; // 下一页
- } else {
- nextPage = currPage;
- }
- //开始索引
- if (currPage > pageCount) {
- begindex = (pageCount - 1) * pageSize;
- } else {
- begindex = (currPage - 1) * pageSize;
- }
- //结束索引
- if(currPage*pageSize>totalSize){
- endindex = totalSize ;
- }else{
- endindex=currPage*pageSize ;
- }
- pagebean.setPrePage(prePage);
- pagebean.setPageSize(pageSize);
- pagebean.setCurrPage(currPage);
- pagebean.setTotalSize(totalSize);
- pagebean.setPageCount(pageCount);
- pagebean.setLastPage(pageCount);
- pagebean.setNextPage(nextPage);
- pagebean.setBeginIndex(begindex) ;
- pagebean.setEndIndex(endindex) ;
- return pagebean;
- }
- }
3、由此就可以在action里面调用了。
- package com.beckham.struts.actions;
- import java.util.List;
- import java.util.Map;
- import org.apache.struts2.interceptor.RequestAware;
- import com.beckham.model.User;
- import com.beckham.page.PageBean;
- import com.beckham.page.PageMessage;
- import com.beckham.service.UserService;
- import com.opensymphony.xwork2.ActionSupport;
- @SuppressWarnings("serial")
- public class UserListAction extends ActionSupport implements RequestAware {
- private UserService userService;
- private int currPage;
- @SuppressWarnings("unchecked")
- private Map request;
- private String path;
- private String password ;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- @SuppressWarnings( { "unchecked", "unchecked" })
- public String execute() throws Exception {
- //查询结果集总数
- String hqlSize = "select count(*) from User";
- //查询目标结果集
- String hql = "from User";
- if (currPage == 0) {
- currPage = 1;
- }
- //获取分页信息
- PageBean pageBean = PageMessage.getPageMessage(currPage, userService.gettotalSize(hqlSize));
- /*
- *
- *获取结果集,这里是和hibernate结合使用,所以参数需要传一个beginIndex
- * pageSize写在配置文件里面,所以这里就不用当做参数传递了
- */
- List<User> list = userService.queryUser(hql, pageBean.getBeginIndex());
- StringBuffer sb = new StringBuffer();
- //带有参数的URL
- sb.append("userlist.action?password=").append(password).append("&") ;
- path = sb.toString();
- request.put("users", list);
- request.put("path", path) ;
- request.put("pageBean", pageBean);
- return SUCCESS;
- }
- public UserService getUserService() {
- return userService;
- }
- public void setUserService(UserService userService) {
- this.userService = userService;
- }
- @SuppressWarnings("unchecked")
- public void setRequest(Map request) {
- this.request = request;
- }
- @SuppressWarnings("unchecked")
- public Map getRequest() {
- return request;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- }
当然在调用的时候需要调用service里面的2个方法 gettotalSize(hqlSize) 和queryUser(hql, pageBean.getBeginIndex())
这2个方法的作用是获取结果集的总记录数和 获取本次查询的结果集,具体实现如下:
- public int gettotalSize(String hql) throws Exception {
- int totalsize = 0;
- try {
- totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql)
- .get(0).toString());
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception("查询用户总数失败", e);
- }
- return totalsize;
- }
- public List<User> queryUser(String hql, int beginIndex) throws Exception {
- try {
- return (List<User>) this.getHibernateTemplate().getSessionFactory()
- .getCurrentSession().createQuery(hql).setFirstResult(
- beginIndex).setMaxResults(
- PropertyUtil.getPageSize()).list();
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception("查询用户出现异常", e);
- }
- }
实现里面的PropertyUtil.getPageSize() 方法是从配置文件里面读取pageSize
- pageSize=5
- downloadPath=img/
- pageNumber=10
PropertyUtil.java
- package com.beckham.util;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- public class PropertyUtil {
- private static Properties p = new Properties() ;
- private static InputStream inputStream = null ;
- static {
- inputStream = PropertyUtil.class.getResourceAsStream("/page.properties") ;
- try {
- p.load(inputStream) ;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static int getPageSize(){
- return Integer.parseInt(p.getProperty("pageSize"));
- }
- public static int getPageNumber(){
- return Integer.parseInt(p.getProperty("pageNumber"));
- }
- public static String getDownloadPath(){
- return p.getProperty("downloadPath");
- }
- public static void main(String[] args) {
- System.out.println(getPageSize());
- }
- }
到此,分页的逻辑已经算是完成了,主要实现是利用了hibernateTemplate来实现查询,所以在查询的时候其实只需要setFirstResult ,setMaxResults就可以,也就是从什么地方开始取,每次最多取多少条记录!
接下来就是写标签了
- package com.tag;
- import java.io.IOException;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.JspWriter;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- import com.beckham.util.PropertyUtil;
- /**
- * @author beckham 分页标签 Oct 22, 2009 9:20:49 PM
- */
- public class PageTag extends SimpleTagSupport {
- private String path; // 请求路径
- private String param; // 传递参数
- private int currPage; // 当前页
- private int totalPage;// 总页数
- private int totalSize;
- private int pageCount;
- private int pageSize;
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- public int getPageCount() {
- return pageCount;
- }
- public void setPageCount(int pageCount) {
- this.pageCount = pageCount;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- public String getParam() {
- return param;
- }
- public void setParam(String param) {
- this.param = param;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- public int getTotalPage() {
- return totalPage;
- }
- public void setTotalPage(int totalPage) {
- this.totalPage = totalPage;
- }
- public void doTag() throws JspException, IOException {
- JspWriter out = this.getJspContext().getOut();
- StringBuffer sb = new StringBuffer();
- sb.append("<mce:style type=/"text/css/"><!--
- ") ;
- sb.append("* { margin:0; padding:0;}") ;
- sb.append("body { font-size:13px; font-family:Verdana;width:100%;}") ;
- sb.append("a { color:#333; text-decoration:none;}") ;
- sb.append("a:hover {text-decoration:none;color:#FF0000;font-weight:bold;}");
- sb.append("ul { list-style:none;}") ;
- sb.append("#pagelist {width:100%; margin:30px auto; padding:6px 0px; height:20px;}") ;
- sb.append("#pagelist ul li { float:left; border:1px solid #5d9cdf; height:20px; line-height:20px; margin:0px 2px;}") ;
- sb.append("#pagelist ul li a, .pageinfo { display:block; padding:0px 6px; background:#e6f2fe;}") ;
- sb.append(".current { background:#a9d2ff; display:block; padding:0px 6px; font-weight:bold;}") ;
- sb.append("
- --></mce:style><style type=/"text/css/" mce_bogus="1">") ;
- sb.append("* { margin:0; padding:0;}") ;
- sb.append("body { font-size:13px; font-family:Verdana;width:100%;}") ;
- sb.append("a { color:#333; text-decoration:none;}") ;
- sb.append("a:hover {text-decoration:none;color:#FF0000;font-weight:bold;}");
- sb.append("ul { list-style:none;}") ;
- sb.append("#pagelist {width:100%; margin:30px auto; padding:6px 0px; height:20px;}") ;
- sb.append("#pagelist ul li { float:left; border:1px solid #5d9cdf; height:20px; line-height:20px; margin:0px 2px;}") ;
- sb.append("#pagelist ul li a, .pageinfo { display:block; padding:0px 6px; background:#e6f2fe;}") ;
- sb.append(".current { background:#a9d2ff; display:block; padding:0px 6px; font-weight:bold;}") ;
- sb.append("</style>") ;
- sb.append("<div id=/"pagelist/">");
- sb.append("<ul>") ;
- if (currPage == 1) {
- sb.append("<li>") ;
- sb.append("首页");
- sb.append("</li>") ;
- sb.append("<li>") ;
- sb.append("上一页");
- sb.append("</li>") ;
- } else {
- sb.append("<li>") ;
- sb.append("<a href="/" mce_href="/""");
- sb.append(path);
- sb.append(param);
- sb.append("=1");
- sb.append("/"");
- sb.append(">");
- sb.append("首页");
- sb.append("</a>");
- sb.append("</li>") ;
- sb.append("<li>") ;
- sb.append("<a href="/" mce_href="/""");
- sb.append(path);
- sb.append(param);
- sb.append("=");
- sb.append(currPage - 1);
- sb.append("/"");
- sb.append(">");
- sb.append("上一页");
- sb.append("</a>");
- sb.append("</li>") ;
- }
- // 显示页码 默认显示pageNumber个页码
- int pageNumber = PropertyUtil.getPageNumber();
- // 总页数小于需要显示的页码数
- int result = (currPage-1) / pageNumber;
- int begin = 1;
- int end = 1;
- begin = result * pageNumber+1;
- end = (result + 1) * pageNumber;
- if (end >= totalPage) {
- end = totalPage;
- }
- for (int i = begin; i <currPage; i++) {
- sb.append("<li>").append("<a href="/" mce_href="/""").append(path).append(param).append("=")
- .append(i).append("/"").append("></a>").append(i).append(
- "</a>").append("</li>");
- }
- sb.append("<li class=/"current/">").append(currPage).append("</li>");
- for (int i = currPage+1; i <=end; i++) {
- sb.append("<li>").append("<a href="/" mce_href="/""").append(path).append(param).append("=")
- .append(i).append("/"").append("></a>").append(i).append(
- "</a>").append("</li>");
- }
- if (currPage == totalPage) {
- sb.append("<li>") ;
- sb.append("下一页");
- sb.append("</li>") ;
- sb.append("<li>") ;
- sb.append("末页");
- sb.append("</li>") ;
- } else {
- sb.append("<li>") ;
- sb.append("<a href="/" mce_href="/""");
- sb.append(path);
- sb.append(param);
- sb.append("=");
- sb.append(currPage + 1);
- sb.append("/"");
- sb.append(">");
- sb.append("下一页");
- sb.append("</a>");
- sb.append("</li>") ;
- sb.append("<li>") ;
- sb.append("<a href="/" mce_href="/""");
- sb.append(path);
- sb.append(param);
- sb.append("=");
- sb.append(totalPage);
- sb.append("/"");
- sb.append(">");
- sb.append("末页");
- sb.append("</a>");
- sb.append("</li>") ;
- }
- sb.append("<li>") ;
- sb.append(" ");
- sb.append("总共");
- sb.append("<font color=/"red/">");
- sb.append(totalSize);
- sb.append("</font>");
- sb.append("条结果");
- sb.append(" ");
- sb.append(" ");
- sb.append("当前");
- sb.append("<font color=/"red/">");
- sb.append(currPage);
- sb.append("</font>");
- sb.append("/");
- sb.append("<font color=/"red/">");
- sb.append(pageCount);
- sb.append("页") ;
- sb.append("</font>");
- sb.append("</li>") ;
- sb.append(" ");
- sb.append("</ul>") ;
- sb.append("</div>");
- out.println(sb);
- }
- }
标签写完,当然就是写tld文件了
- <?xml version="1.0" encoding="UTF-8" ?>
- <taglib 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-jsptaglibrary_2_1.xsd"
- version="2.1">
- <tlib-version>1.1</tlib-version>
- <short-name>pageTag</short-name>
- <uri>/WEB-INF/pagetag.tld</uri>
- <tag>
- <name>pageInfo</name>
- <tag-class>com.tag.PageTag</tag-class>
- <body-content>empty</body-content>
- <attribute>
- <name>path</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>currPage</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>param</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>totalPage</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>totalSize</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>pageCount</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>pageSize</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- </tag>
- </taglib>
最后的一步就是在页面上显示查询结果和用标签显示分页信息
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib uri="/struts-tags" prefix="s"%>
- <%@ taglib uri="/WEB-INF/pagetag.tld" prefix="pt"%>
- <%
- 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 'mess.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">
- </head>
- <body>
- <div>
- <table border="1" style="width: 100%" align="center">
- <tr>
- <td>
- id
- </td>
- <td>
- 用户名
- </td>
- <td>
- 姓名
- </td>
- <td>
- 年龄
- </td>
- <td>
- 性别
- </td>
- <s:iterator id="user" value="#request.users">
- <tr>
- <td>
- <s:property value="#user.id" />
- </td>
- <td>
- <s:property value="#user.username" />
- </td>
- <td>
- <s:property value="#user.realname" />
- </td>
- <td>
- <s:property value="#user.age" />
- </td>
- <td>
- <s:property value="#user.sex" />
- </td>
- </tr>
- </s:iterator>
- </tr>
- <tr>
- </table>
- </div>
- <div style="width: 100%">
- <pt:pageInfo pageCount="${pageBean.pageCount }"
- currPage="${pageBean.currPage }"
- param="currPage"
- path="${path}"
- totalPage="${pageBean.lastPage }"
- pageSize="${pageBean.pageSize }"
- totalSize="${pageBean.totalSize }"
- />
- </div>
- </body>
- </html>
显示效果由于图片无法上传,所以也就贴不上来了!