SSH:Struts2.2+Hibernate3.6+Spring3.1整合分页示例



SSH:Struts2.2+Hibernate3.6+Spring3.1分页示例.

参考资料
1 ssh分页(多个例子)
http://useryouyou.iteye.com/blog/593954
2 ssh2分页例子
http://459104018-qq-com.iteye.com/blog/467196
3 ssh2分页
http://blog.csdn.net/shmily2038/archive/2009/12/28/5090044.aspx
注意事项:
此示例是在:Struts2.2+Spring3.1+Hibernate3.6整合(登录示例及CRUD操作)基础上加的分页功能:
http://liuzidong.iteye.com/blog/935493
实现功能:分页,排序,设置每页显示多少条,转到第多少页
调用说明:
1  导入只需要:com.liuzd.page包下的类或者将page.jar加入WEB-INF/lib下也行^_^
2  Struts2前台类实现: BaseAction父类
3  在子类方法中调用父类提供的方法:
Page page = executePage(querySql,totalCount,” id desc “);
需要传递三个参数就行了: querySql(查询sql语句), totalCount(总行数),
” id desc “(排序的列名与排序方式)
4 返回分页数据
List<User> users = this.userService.getUserListByPage(page);
5 在spring配置文件中请保持有: jdbcTemplate与hibernateTemplate这二个Bean的名字,否则dbUtil类不能使用
6 具体可参见:四的说明
一 运行环境:XP+Myeclipse6.6+WebLogic92+Oracle10g
二 工程相关图片:
1 DEMO图片

2 工程代码图片

3 page.jar图片

三 此示例是在:
Struts2.2+Spring3.1+Hibernate3.6整合(登录示例及CRUD操作)基础上加的分页功能:
http://liuzidong.iteye.com/blog/935493,jar包在此页面中下载
四 关注类及页面:
1 BaseAction类(可能你在项目有其它的父类要使用,只要关注这个类中的: protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc)方法就行了,方法中的参数不用修改,它来自于page.jsp,你可拷贝这个方法到你的父类中就实现了分页功能,分页类详见注释)
2 UserAction子类(只关注:方法:userList()中的调用方式)
3 UserDAOImpl类(关注方法:public List<User> getUserListByPage(final Page page) )
4 userList.jsp页面

Java代码  收藏代码
  1. <%@ taglib uri=”/WEB-INF/c.tld” prefix=”c”%>
  2. <c:set var=”page” value=”${sessionScope.page}” />

在排序处:

Java代码  收藏代码
  1. <font color=’red’>${page.sortName eq ”username” ? page.sortInfo :page.defaultInfo}</font>

在下面加上:

Java代码  收藏代码
  1. <jsp:include page=”/page/page.jsp”>
  2.     <jsp:param name=”url” value=”userAction!userList.action” />
  3.     <!– 演示传值:要用%26 –>
  4.     <jsp:param name=”urlParams” value=”%26age=2″ />
  5. </jsp:include>

四 要关注的类与页面

1 BaseAction.java

Java代码  收藏代码
  1. package com.liuzd.common;
  2. import java.util.Map;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.ServletActionContext;
  5. import org.apache.struts2.interceptor.SessionAware;
  6. import com.liuzd.page.Page;
  7. import com.liuzd.page.PageUtil;
  8. import com.liuzd.page.PageState;
  9. import com.opensymphony.xwork2.ActionContext;
  10. import com.opensymphony.xwork2.ActionSupport;
  11. /**
  12.  * 基本Struts2的分页父类
  13.  * @author liuzd
  14.  * @version 1.0 2011-05-12
  15.  * @since JDK1.5
  16.  * */
  17. public class BaseAction extends ActionSupport implements SessionAware{
  18.     private static final long serialVersionUID = 1L;
  19.     public void setSession(Map<String, Object> sessionMap) {
  20.     }
  21.     protected Map<String,Object> getMapSession(){
  22.         return  (Map<String,Object>)ActionContext.getContext().getSession();
  23.     }
  24.     protected Object getMapSessionGet(String key){
  25.         return  getMapSession().get(key);
  26.     }
  27.     protected void setMapSessionPut(String key,Object value){
  28.          getMapSession().put(key, value);
  29.     }
  30.     /***
  31.      * 获取请求对象
  32.      * */
  33.     protected HttpServletRequest getRequest(){
  34.         return ServletActionContext.getRequest ();
  35.     }
  36.     /***
  37.      * 获取会话对象
  38.      * */
  39.     protected javax.servlet.http.HttpSession getSession(){
  40.         return getRequest().getSession();
  41.     }
  42.     /***
  43.      * 设置请求参数
  44.      * */
  45.     protected void setRequestAttribute(String attribute,Object attrValue){
  46.         getRequest().setAttribute(attribute, attrValue);
  47.     }
  48.     /***
  49.      * 获取请求参数
  50.      * */
  51.     protected Object getRequestAttribute(String attribute){
  52.         return getRequest().getAttribute(attribute);
  53.     }
  54.     /***
  55.      * 设置Session参数与值
  56.      * */
  57.     protected void setSessionAttribute(String attribute,Object attrValue){
  58.         getSession().setAttribute(attribute, attrValue);
  59.     }
  60.     /***
  61.      * 获取Session参数与值
  62.      * */
  63.     protected Object getSessionAttribute(String attribute){
  64.         return getSession().getAttribute(attribute);
  65.     }
  66.     /**
  67.      * oracel的三层分页语句
  68.      * 子类在展现数据前,进行分页计算!
  69.      * @param querySql  查询的SQL语句,未进行分页
  70.      * @param totalCount 根据查询SQL获取的总条数
  71.      * @param columnNameDescOrAsc 列名+排序方式 : ID DESC or ASC
  72.      */
  73.     protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc){
  74.         String oracleSql = PageUtil.createQuerySql(querySql,columnNameDescOrAsc);
  75.         if(null == totalCount){
  76.             totalCount = 0L;
  77.         }
  78.         /**页面状态,这个状态是分页自带的,与业务无关*/
  79.         String pageAction = getRequest().getParameter(“pageAction”);
  80.         String value = null;
  81.         /**获取下标判断分页状态*/
  82.         int index = PageState.getOrdinal(pageAction);
  83.         if(0 == index){
  84.             /**每页显示多少条*/
  85.             value = getRequest().getParameter(“everyPage”);
  86.         }
  87.         Page page = null;
  88.         /**
  89.          * index < 1 只有二种状态
  90.          * 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1
  91.          * 2 当页面设置每页显示多少条: index=0,当每页显示多少条时,分页类要重新计算
  92.          * */
  93.         if(index < 1){
  94.             page = PageUtil.inintPage(oracleSql,totalCount,index,value,getPage());
  95.         }else{
  96.             /**
  97.              * 当页面排序时
  98.              * */
  99.             if(5 == index){
  100.                 value = getRequest().getParameter(“sortName”);
  101.             /**
  102.              * 到指定多少页
  103.              * */
  104.             }else if(6 == index){
  105.                 value = getRequest().getParameter(“currentPage”);
  106.             }
  107.             page = PageUtil.execPage(index,value,getPage());
  108.         }
  109.         setSession(page);
  110.         return page;
  111.     }
  112.     private Page getPage() {
  113.         Page page = (Page)getSession().getAttribute(PageUtil.SESSION_PAGE_KEY);
  114.         if(page == null){
  115.             page = new Page();
  116.         }
  117.         return page;
  118.     }
  119.     private void setSession(Page page) {
  120.         getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page);
  121.     }
  122. }

2 UserAction.java

Java代码  收藏代码
  1. package com.liuzd.s2sh.web;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.springframework.context.annotation.Scope;
  5. import org.springframework.stereotype.Component;
  6. import com.liuzd.common.BaseAction;
  7. import com.liuzd.common.DbUtils;
  8. import com.liuzd.page.Page;
  9. import com.liuzd.s2sh.entity.User;
  10. import com.liuzd.s2sh.service.UserService;
  11. @Component(“u”)
  12. @Scope(“prototype”)
  13. public class UserAction extends BaseAction {
  14.     private static final long serialVersionUID = 1L;
  15.     private String message = null;
  16.     private User user = null;
  17.     private String action = null;
  18.     public String getAction() {
  19.         return action;
  20.     }
  21.     public void setAction(String action) {
  22.         this.action = action;
  23.     }
  24.     public User getUser() {
  25.         return user;
  26.     }
  27.     public void setUser(User user) {
  28.         this.user = user;
  29.     }
  30.     @Override
  31.     public String execute() throws Exception {
  32.         System.out.println(“user: ” + user);
  33.         User dbUser = this.userService.checkUserExits(user);
  34.         if (null != dbUser) {
  35.             message = ”用户: ” + user.getUsername() + ”登录成功”;
  36.             System.out.println(message);
  37.             getMapSession().put(“sessionUser”, dbUser);
  38.             return userList();
  39.             //return ”success”;
  40.         }
  41.         message = ”用户: ” + user.getUsername() + ”登录失败”;
  42.         return ”fail”;
  43.     }
  44.     public String loadUser() {
  45.         action = ”update”;
  46.         message = ”编辑用户信息”;
  47.         User loadUser = new User();
  48.         loadUser.setId(user.getId());
  49.         user = this.userService.getUserByUid(loadUser);
  50.         this.getRequest().setAttribute(“myname”, ”天涯海角”);
  51.         this.getMapSession().put(“mysex”, ”男”);
  52.         System.out.println(“loaduser: ” + user);
  53.         return ”user”;
  54.     }
  55.     public String addUser() {
  56.         action = ”add”;
  57.         return ”user”;
  58.     }
  59.     public String saveUser() {
  60.         this.userService.addUser(user);
  61.         return ”user”;
  62.     }
  63.     public String delUser() {
  64.         action = ”del”;
  65.         this.userService.delUser(user);
  66.         return userList();
  67.     }
  68.     public String editUser() {
  69.         System.out.println(“action: ” + action + ”,编辑用户: ” + user);
  70.         if (“update”.equals(action)) {
  71.             this.userService.editUser(user);
  72.         } else if (“add”.equals(action)) {
  73.             saveUser();
  74.         }
  75.         return userList();
  76.     }
  77.     public String getMessage() {
  78.         return message;
  79.     }
  80.     public void setMessage(String message) {
  81.         this.message = message;
  82.     }
  83.     private UserService userService = null;
  84.     private DbUtils dbUtil = null;
  85.     public String userList() {
  86.         //因为Hibernate分页的性能问题,使用原生sql来解决
  87.         String querySql = ”select * from users where 1=1 ”;
  88.         //用jdbc查询总条数
  89.         Long totalCount = getDbUtil().getCountByQuerySql(querySql);
  90.         //调用父类方法进行分页参数相关计算
  91.         Page page = executePage(querySql,totalCount,” id desc ”);
  92.         //返回分页数据
  93.         List<User> users = this.userService.getUserListByPage(page);
  94.         getRequest().setAttribute(“userList”,users);
  95.         return ”userList”;
  96.     }
  97.     public UserService getUserService() {
  98.         return userService;
  99.     }
  100.     @Resource
  101.     public void setUserService(UserService userService) {
  102.         this.userService = userService;
  103.     }
  104.     public DbUtils getDbUtil() {
  105.         return dbUtil;
  106.     }
  107.     @Resource
  108.     public void setDbUtil(DbUtils dbUtil) {
  109.         this.dbUtil = dbUtil;
  110.     }
  111. }

3 UserDAOImpl.java

Java代码  收藏代码
  1. package com.liuzd.s2sh.dao.impl;
  2. import java.sql.SQLException;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import org.hibernate.HibernateException;
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;
  8. import org.springframework.orm.hibernate3.HibernateCallback;
  9. import org.springframework.orm.hibernate3.HibernateTemplate;
  10. import org.springframework.stereotype.Component;
  11. import com.liuzd.page.Page;
  12. import com.liuzd.s2sh.dao.UserDAO;
  13. import com.liuzd.s2sh.entity.User;
  14. @Component(“userDao”)
  15. public class UserDAOImpl implements UserDAO {
  16.     private HibernateTemplate hibernateTemplate;
  17.     public HibernateTemplate getHibernateTemplate() {
  18.         return hibernateTemplate;
  19.     }
  20.     @Resource
  21.     public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
  22.         this.hibernateTemplate = hibernateTemplate;
  23.     }
  24.     @SuppressWarnings(“unchecked”)
  25.     public User getUserByUserIdAndUserNameExits(User user) {
  26.         List<User> users = hibernateTemplate
  27.                 .find(“from User u where u.username = ’” + user.getUsername()
  28.                         + ”‘ and u.password=’” + user.getPassword() + ”‘”);
  29.         if (users != null && users.size() > 0) {
  30.             return users.get(0);
  31.         }
  32.         return null;
  33.     }
  34.     public void saveUser(User user) {
  35.         this.hibernateTemplate.save(user);
  36.     }
  37.     public void delUser(User user) {
  38.         User delUser = getUser(user);
  39.         this.hibernateTemplate.delete(delUser);
  40.     }
  41.     @SuppressWarnings(“unchecked”)
  42.     public List<User> finUserAll() {
  43.         return this.hibernateTemplate.find(“from User”);
  44.     }
  45.     public User getUser(User user) {
  46.         return this.hibernateTemplate.get(User.class, user.getId());
  47.     }
  48.     public void updateUser(User user) {
  49.         this.hibernateTemplate.update(user);
  50.     }
  51.     @SuppressWarnings(“unchecked”)
  52.     public Long getUserCount() {
  53.         List list = this.getHibernateTemplate().find(“select count(*) from User”);
  54.         return ((Long) list.iterator().next());
  55.     }
  56.     public Long getUserCount(String querySql) {
  57.         return (Long) getHibernateTemplate().find(querySql).iterator().next();
  58.     }
  59.     @SuppressWarnings(“unchecked”)
  60.     public List<User> getUserListByPage(final Page page) {
  61.         return this.getHibernateTemplate().executeFind(new HibernateCallback() {
  62.         public Object doInHibernate(Session session)
  63.             throws HibernateException, SQLException {
  64.                 /*Query query = session.createQuery(“from User”);
  65.                 //性能问题所在
  66.                 query.setFirstResult(page.getBeginIndex());
  67.                 query.setMaxResults(page.getEveryPage());
  68.                 return query.list();*/
  69.                 /*  .add(Restrictions.gt(“id”, 2)) //greater than = id > 2
  70.                      .add(Restrictions.lt(“id”, 8)) //little than = id < 8
  71.                      .add(Restrictions.like(“title”, ”t_”))
  72.                      .createCriteria(“category”)
  73.                      .add(Restrictions.between(“id”, 3, 5)) //category.id >= 3 and category.id <=5
  74.                    .add(Expression.ge(“age”, new Integer(20));
  75.                    .addOrder( Order.asc(“name”) )
  76.                    .addOrder( Order.desc(“age”) )
  77.                    .setMaxResults(50)
  78.                    .list();
  79.                    .add( Property.forName(“name”).like(“F%”) )
  80.                    .addOrder( Property.forName(“name”).asc() )
  81.                    .addOrder( Property.forName(“age”).desc() )
  82.                    .setMaxResults(50)
  83.                    .list();
  84.                  * */
  85.                 /*Criteria c = session.createCriteria(User.class);
  86.                 String sortName = page.getSortName();
  87.                 if(StringUtils.isNotEmpty(sortName)){
  88.                     if(“asc”.equals(page.getSortState())){
  89.                         c.addOrder(org.hibernate.criterion.Order.asc(sortName));
  90.                     }else{
  91.                         c.addOrder(org.hibernate.criterion.Order.desc(sortName));
  92.                     }
  93.                 }
  94.                 c.setFirstResult(page.getBeginIndex());
  95.                 c.setMaxResults(page.getEveryPage());
  96.                 return c.list();*/
  97.                 Query query = session.createSQLQuery(page.getQuerySql()).addEntity(User.class);
  98.                 return query.list();
  99.             }
  100.         });
  101.     }
  102. }


5  JSP引用

Java代码  收藏代码
  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8″  pageEncoding=”UTF-8″%>
  2. <%@ taglib prefix=”s” uri=”/struts-tags”%>
  3. <%@ taglib uri=”/WEB-INF/c.tld” prefix=”c”%>
  4. <c:set var=”page” value=”${sessionScope.page}” />
  5. <html>
  6.     <head>
  7.         <title>用户集合</title>
  8.     </head>
  9.     <body>
  10.         <table width=”60%” border=”1″ cellpadding=”0″ align=”center”>
  11.             <thead>
  12.                 <tr>
  13.                     <th style=”cursor: hand;” title=”按姓名进行排序” onclick=”sortPage(‘username’)” valign=”top”>
  14.                         姓名<font color=’red’>${page.sortName eq ”username” ? page.sortInfo : page.defaultInfo}</font>
  15.                     </th>
  16.                     <th style=”cursor: hand;” title=”按年龄进行排序” onclick=”sortPage(‘age’)” valign=”top”>
  17.                         年龄<font color=’red’>${page.sortName eq ”age” ? page.sortInfo : page.defaultInfo}</font>
  18.                     </th>
  19.                     <th style=”cursor: hand;” title=”按性别进行排序” onclick=”sortPage(‘sex’)” valign=”top”>
  20.                         性别<font color=’red’>${page.sortName eq ”sex” ? page.sortInfo : page.defaultInfo}</font>
  21.                     </th>
  22.                     <th style=”cursor: hand;” title=”按地址进行排序” onclick=”sortPage(‘address’)” valign=”top”>
  23.                         地址<font color=’red’>${page.sortName eq ”address” ? page.sortInfo : page.defaultInfo}</font>
  24.                     </th>
  25.                     <th style=”cursor: hand;” >
  26.                         操作
  27.                     </th>
  28.                 </tr>
  29.             </thead>
  30.             <tbody>
  31.                 <!–
  32.                   <s:iterator value=”#request.userList” status=”status” >
  33.                     <tr align=”center”>
  34.                       <td><s:property value=”username”/></td>
  35.                       <td><s:property value=”age”/></td>
  36.                       <td><s:property value=”sex”/></td>
  37.                       <td><s:property value=”address”/></td>
  38.                       <td>
  39.                         <s:a href=”userAction!addUser.action”>添加</s:a> | <s:a href=”userAction!loadUser.action?user.id=%{id}”>编辑</s:a> |
  40.                         <a href=”<s:url action=”userAction!delUser.action”><s:param name=”user.id” value=”id”/></s:url>”>删除</a>
  41.                       </td>
  42.                     </tr>
  43.                  </s:iterator>
  44.                 –>
  45.                 <c:forEach items=”${requestScope.userList}” var=”user”>
  46.                     <tr align=”center”>
  47.                         <td>
  48.                             ${user.username}
  49.                         </td>
  50.                         <td>
  51.                             ${user.age}
  52.                         </td>
  53.                         <td>
  54.                             ${user.sex eq 1 ? ”男” : user.sex eq 2 ? ”女” : ”未知”}
  55.                         </td>
  56.                         <td>
  57.                             ${user.address}
  58.                         </td>
  59.                         <td>
  60.                             <a
  61.                                 href=”${pageContext.request.contextPath}/userAction!addUser.action”>添加</a>
  62.                             |
  63.                             <a
  64.                                 href=”${pageContext.request.contextPath}/userAction!loadUser.action?user.id=${user.id}”>编辑</a>
  65.                             |
  66.                             <a
  67.                                 href=”${pageContext.request.contextPath}/userAction!delUser.action?user.id=${user.id}”>删除</a>
  68.                         </td>
  69.                     </tr>
  70.                 </c:forEach>
  71.                 <jsp:include page=”page.jsp”>
  72.                     <jsp:param name=”url” value=”userAction!userList.action” />
  73.                     <!– 演示传值:要用%26 –>
  74.                     <jsp:param name=”urlParams” value=”%26age=2″ />
  75.                 </jsp:include>
  76.             </tbody>
  77.         </table>
  78.         <br>
  79.         <a href=”${pageContext.request.contextPath}/Login.jsp”>返回</a>
  80.         <br>
  81.         <s:debug></s:debug>
  82.     </body>
  83. </html>

五 你不需要关注的分页类与JSP页面,可在附件下载jar与源码
1 Page.java

Java代码  收藏代码
  1. package com.liuzd.page;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.apache.commons.lang3.builder.ToStringBuilder;
  4. /**
  5.  * 分页类
  6.  * @author liuzd
  7.  * @version 1.0 2011-05-12
  8.  * @since JDK1.5
  9.  * */
  10. public class Page implements java.io.Serializable{
  11.     private static final long serialVersionUID = 1L;
  12.     //前一页
  13.     private Boolean hasPrePage;
  14.     //后一页
  15.     private Boolean hasNextPage;
  16.     //每页显示多少条:默认10条
  17.     private Long everyPage = 10L;
  18.     //总页数
  19.     private Long totalPage;
  20.     //当前第多少页:默认第1页
  21.     private Long currentPage = 1L;
  22.     //开始下标
  23.     private Long beginIndex;
  24.     //结束下标
  25.     private Long endinIndex;
  26.     //总共多少条
  27.     private Long totalCount;
  28.     //查询结果集语句
  29.     private String querySql;
  30.     //未进行分页的语句
  31.     private String initQuerySql;
  32.     //排序列名
  33.     private String sortName;
  34.     //排序状态
  35.     private String sortState;
  36.     //排序信息
  37.     private String sortInfo;
  38.     //是否排序
  39.     private Boolean sort;
  40.     private String defaultInfo = ”&nbsp;&nbsp;”;
  41.     public String getDefaultInfo() {
  42.         return defaultInfo;
  43.     }
  44.     public void setDefaultInfo(String defaultInfo) {
  45.         this.defaultInfo = defaultInfo;
  46.     }
  47.     public String getSortInfo() {
  48.         return sortInfo;
  49.     }
  50.     public void setSortInfo(String sortInfo) {
  51.         this.sortInfo = sortInfo;
  52.     }
  53.     public String getSortName() {
  54.         return sortName;
  55.     }
  56.     public void setSortName(String sortName) {
  57.         setPageSortState(sortName);
  58.     }
  59.     public String getSortState() {
  60.         return sortState;
  61.     }
  62.     public void setSortState(String sortState) {
  63.         this.sortState = sortState;
  64.     }
  65.     public String getQuerySql() {
  66.         return querySql;
  67.     }
  68.     public void setQuerySql(String querySql) {
  69.         this.querySql = querySql;
  70.     }
  71.     public Page() {
  72.     }
  73.     /**
  74.      * 常用,用于计算分页
  75.      * */
  76.     public Page(Long totalRecords){
  77.         this.totalCount = totalRecords;
  78.         setTotalPage(getTotalPage(totalRecords));
  79.     }
  80.     /**
  81.      * 设置每页显示多少条时使用
  82.      * */
  83.     public Page(Long everyPage,Long totalRecords){
  84.         this.everyPage = everyPage;
  85.         this.totalCount = totalRecords;
  86.         setTotalPage(getTotalPage(totalRecords));
  87.     }
  88.     /**
  89.      * @param state   状态码
  90.      * @param value   到第多少页或者设置每页显示多少条或者为排序列名
  91.      */
  92.     public void pageState(int  index,String value) {
  93.         sort = false;
  94.         switch (index) {
  95.         case 0 :setEveryPage(Long.parseLong(value));break;
  96.         case 1 :first();break;
  97.         case 2: previous();break;
  98.         case 3: next();break;
  99.         case 4: last();break;
  100.         case 5: sort = true;sort(value);break;
  101.         case 6 ://到指定第多少页
  102.             setCurrentPage(Long.parseLong(value));
  103.             break;
  104.         }
  105.     }
  106.     /**
  107.      * 最前一页
  108.      */
  109.     private void first() {
  110.         currentPage = 1L;
  111.     }
  112.     private void previous() {
  113.         currentPage–;
  114.     }
  115.     private void next() {
  116.         currentPage++;
  117.     }
  118.     private void last() {
  119.         currentPage = totalPage;
  120.     }
  121.     private void sort(String sortName) {
  122.         //设置排序状态
  123.         setPageSortState(sortName);
  124.     }
  125.     /**
  126.      * 计算总页数
  127.      * */
  128.     private Long getTotalPage(Long totalRecords) {
  129.          Long totalPage = 0L;
  130.          if (totalRecords % everyPage == 0)
  131.            totalPage = totalRecords / everyPage;
  132.          else {
  133.            totalPage = totalRecords / everyPage + 1;
  134.          }
  135.          return totalPage;
  136.     }
  137.     public Long getBeginIndex() {
  138.         this.beginIndex = (currentPage - 1) * everyPage;
  139.         return this.beginIndex;
  140.     }
  141.     public void setBeginIndex(Long beginIndex) {
  142.         this.beginIndex = beginIndex;
  143.     }
  144.     public Long getCurrentPage() {
  145.         this.currentPage = currentPage == 0 ? 1 : currentPage;
  146.         return this.currentPage;
  147.     }
  148.     public void setCurrentPage(Long currentPage) {
  149.         if(0 == currentPage){
  150.             currentPage = 1L;
  151.         }
  152.         this.currentPage = currentPage;
  153.     }
  154.     public Long getEveryPage() {
  155.         this.everyPage = everyPage == 0 ? 10 : everyPage;
  156.         return this.everyPage;
  157.     }
  158.     public void setEveryPage(Long everyPage) {
  159.         this.everyPage = everyPage;
  160.     }
  161.     public Boolean getHasNextPage() {
  162.         this.hasNextPage = (currentPage != totalPage) && (totalPage != 0);
  163.         return this.hasNextPage;
  164.     }
  165.     public void setHasNextPage(Boolean hasNextPage) {
  166.         this.hasNextPage = hasNextPage;
  167.     }
  168.     public Boolean getHasPrePage() {
  169.         this.hasPrePage = currentPage != 1;
  170.         return this.hasPrePage;
  171.     }
  172.     public void setHasPrePage(Boolean hasPrePage) {
  173.         this.hasPrePage = hasPrePage;
  174.     }
  175.     public Long getTotalPage() {
  176.         return this.totalPage;
  177.     }
  178.     public void setTotalPage(Long totalPage) {
  179.         if(this.currentPage > totalPage){
  180.             this.currentPage = totalPage;
  181.         }
  182.         this.totalPage = totalPage;
  183.     }
  184.     public Long getTotalCount() {
  185.         return this.totalCount;
  186.     }
  187.     public void setTotalCount(Long totalCount) {
  188.         setTotalPage(getTotalPage(totalCount));
  189.         this.totalCount = totalCount;
  190.     }
  191.     @Override
  192.     public String toString() {
  193.         return ToStringBuilder.reflectionToString(this);
  194.     }
  195.     /**
  196.      * 设置排序状态
  197.      * */
  198.     private void setPageSortState(String newPageSortName){
  199.         //判断之前的排序字段是否为空
  200.         if(StringUtils.isEmpty(sortName)){
  201.             //默认排序为升序
  202.             this.sortState = PageUtil.ASC;
  203.             this.sortInfo = PageUtil.PAGE_ASC;
  204.         }else{
  205.             if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){
  206.                 //判断sortState排序状态值
  207.                 if(StringUtils.equalsIgnoreCase(sortState, PageUtil.ASC)){
  208.                     this.sortState = PageUtil.DESC;
  209.                     this.sortInfo = PageUtil.PAGE_DESC;
  210.                 }else{
  211.                     this.sortState = PageUtil.ASC;
  212.                     this.sortInfo = PageUtil.PAGE_ASC;
  213.                 }
  214.             }else{
  215.                 //默认
  216.                 this.sortState = PageUtil.ASC;
  217.                 this.sortInfo = PageUtil.PAGE_ASC;
  218.             }
  219.         }
  220.         sortName = newPageSortName.toLowerCase();
  221.     }
  222.     public Boolean isSort() {
  223.         return sort;
  224.     }
  225.     public void setSort(Boolean sort) {
  226.         this.sort = sort;
  227.     }
  228.     public String getInitQuerySql() {
  229.         return initQuerySql;
  230.     }
  231.     public void setInitQuerySql(String initQuerySql) {
  232.         this.initQuerySql = initQuerySql;
  233.     }
  234.     public Long getEndinIndex() {
  235.         this.endinIndex = (currentPage) * everyPage;
  236.         return endinIndex;
  237.     }
  238.     public void setEndinIndex(Long endinIndex) {
  239.         this.endinIndex = endinIndex;
  240.     }
  241. }

2 PageState.java

Java代码  收藏代码
  1. package com.liuzd.page;
  2. import org.apache.commons.lang3.StringUtils;
  3. /**
  4.  * 分页状态类
  5.  * @author liuzd
  6.  * @version 1.0 2011-05-12
  7.  * @since JDK1.5
  8.  * */
  9. public enum PageState {
  10.     /**
  11.      * 设置每页显示多少条
  12.      * */
  13.     SETPAGE,
  14.     /**
  15.      * 首页
  16.      * */
  17.     FIRST,
  18.     /**
  19.      * 向前一页
  20.      * */
  21.     PREVIOUS,
  22.     /**
  23.      * 向后一页
  24.      * */
  25.     NEXT,
  26.     /**
  27.      * 末页
  28.      * */
  29.     LAST,
  30.     /**
  31.      * 排序
  32.      * */
  33.     SORT,
  34.     /**
  35.      * 到第多少页
  36.      * */
  37.     GOPAGE;
  38.     /**
  39.      * @param value 索引名称
  40.      * @return 返回索引下标
  41.      */
  42.     public static int getOrdinal(String value) {
  43.         int index = -1;
  44.         if (StringUtils.isEmpty(value)) {
  45.             return index;
  46.         }
  47.         String newValue = StringUtils.trim(value).toUpperCase();
  48.         try {
  49.             index = valueOf(newValue).ordinal();
  50.         } catch (IllegalArgumentException e) {}
  51.         return index;
  52.     }
  53. }

3 PageUtil.java

Java代码  收藏代码
  1. package com.liuzd.page;
  2. /**
  3.  * 分页工具类
  4.  * @author liuzd
  5.  * @version 1.0 2011-05-12
  6.  * @since JDK1.5
  7.  * */
  8. public class PageUtil {
  9.     public static final String ASC = ”asc”;
  10.     public static final String DESC = ”desc”;
  11.     public static final String PAGE_DESC = ”↓”;
  12.     public static final String PAGE_ASC = ”↑”;
  13.     public static final String PAGE_NULL = ”&nbsp;&nbsp;”;
  14.     public static final String SESSION_PAGE_KEY = ”page”;
  15.     /**
  16.      * @param querySql   查询SQL
  17.      * @param beginIndex 开始下标
  18.      * @param endinIndex 结束下标
  19.      * @return
  20.      */
  21.     public static String getPageQuerySql(String querySql,Long beginIndex, Long endinIndex) {
  22.         if(querySql.indexOf(“where rn>”) != -1 && querySql.indexOf(“and rn<=”) != -1){
  23.             return querySql.toUpperCase();
  24.         }
  25.         return new java.lang.StringBuffer().append(querySql).append(“ where rn>”).append(beginIndex).append(“ and rn<=”).append(endinIndex).toString().toUpperCase();
  26.     }
  27.     /**
  28.      * @param querySql    查询SQL
  29.      * @param orderByName 排序列名
  30.      * @return
  31.      */
  32.     @SuppressWarnings(“unused”)
  33.     public static String createQuerySql(String querySql, String orderByName) {
  34.         StringBuilder sql = new StringBuilder();
  35.         sql.append(“select ttt.* from(select tt.*,rownum rn from(“);
  36.         sql.append(querySql);
  37.         if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderByName)) {
  38.             sql.append(“ order by ”).append(orderByName);
  39.         }
  40.         sql.append(“ )tt)ttt ”);
  41.         return sql.toString();
  42.     }
  43.     /**
  44.      * 取得排序名称+desc or asc
  45.      * @param querySql 查询SQL
  46.      * @return 返回查询语句 SELECT … FROM TABLE  ORDER BY ID DESC 中的 ID DESC
  47.      */
  48.     public static String getSortDescOrAsc(String querySql) {
  49.         /**取得ordery by之前的查询字符串*/
  50.         querySql = querySql.toUpperCase();
  51.         String temp = ”ORDER BY”;
  52.         int orderIndex = querySql.lastIndexOf(temp);
  53.         String newsql = querySql.substring(orderIndex);
  54.         String temp2 = ”)”;
  55.         int lastIndex = newsql.indexOf(temp2);
  56.         String orderByName = newsql.substring(temp.length(),lastIndex).trim();
  57.         return orderByName;
  58.     }
  59.     /**
  60.      * 初始化分页类
  61.      * @param initPageSql  未分页的查询SQL
  62.      * @param totalCount   总行数
  63.      * @param index        分页状态
  64.      * @param value        只有在设置每页显示多少条时,值不会NULL,其它为NULL
  65.      */
  66.     public  static Page inintPage(String initPageSql,Long totalCount,Integer index,String value,Page sessionPage){
  67.         Page page = null;
  68.         if(index < 0){
  69.              page = new Page(totalCount);
  70.         }else{
  71.              /**每页显示多少条*/
  72.              Long everPage = null == value ? 10 : Long.parseLong(value);
  73.              /**获取Session中的分页类,方便保存页面分页状态*/
  74.              page = sessionPage;
  75.              page.setEveryPage(everPage);
  76.              page.setTotalCount(totalCount);
  77.         }
  78.         page.setInitQuerySql(initPageSql);
  79.         /**对查询SQL进行分页计算*/
  80.         String querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
  81.         /**真正传递到后台执行获取分页数据的sql*/
  82.         page.setQuerySql(querySql);
  83.         /**保存到Session中*/
  84.         return page;
  85.     }
  86.     /**
  87.      * 当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作
  88.      * @param index 分页状态
  89.      * @param value 排序字段名或者到第多少页
  90.      */
  91.     public static Page execPage(int  index,String value,Page sessionPage){
  92.         Page page = sessionPage;
  93.         /**调用方法进行分页计算*/
  94.         page.pageState(index,value);
  95.         /**未进行分页前的sql*/
  96.         String initPageSql = page.getInitQuerySql();
  97.         /**进行分页SQL组合*/
  98.         String  querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
  99.         /**替换排序列名*/
  100.         if (page.isSort() == true) {
  101.             String sortName = page.getSortName();
  102.             if (null != sortName) {
  103.                 /**获取排序状态:值(desc or asc)*/
  104.                 String descAsc = page.getSortState();
  105.                 /**组合新的排序字段与状态*/
  106.                 String sortNameDescAsc = (“ ” + sortName + ” ” + descAsc).toUpperCase();
  107.                 /**返回之前的排序字段与状态*/
  108.                 String getOldSortName = PageUtil.getSortDescOrAsc(querySql);
  109.                 /**返回最新的排序字段与状态*/
  110.                 querySql = querySql.replace(getOldSortName,sortNameDescAsc);
  111.             }
  112.         }
  113.         page.setQuerySql(querySql);
  114.         return page;
  115.     }
  116. }

4 page.jsp

Java代码  收藏代码
  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8″  pageEncoding=”UTF-8″%>
  2. <%@ taglib uri=”/WEB-INF/c.tld” prefix=”c”%>
  3. <c:set var=”page” value=”${sessionScope.page}” />
  4. <c:set var=”path” value=”${pageContext.request.contextPath}” />
  5. <c:set var=”url” value=”${param.url}” />
  6. <c:set var=”urlParams” value=”${param.urlParams}” />
  7. <c:set var=”pathurl” value=”${path}/${url}” />
  8. <tr>
  9.     <td colspan=”5″>
  10.         共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条
  11.         当前第${page.currentPage}页&nbsp;
  12.         <c:choose>
  13.             <c:when test=”${page.hasPrePage eq false}”>
  14.                 &lt&lt首页&nbsp;&lt上页&nbsp;
  15.             </c:when>
  16.             <c:otherwise>
  17.                 <a href=”${pathurl}?&pageAction=first${urlParams}”>&lt&lt首页&nbsp;</a>&nbsp;
  18.                 <a href=”${pathurl}?pageAction=previous${urlParams}” />&lt上一页</a>
  19.             </c:otherwise>
  20.         </c:choose>
  21.         &nbsp;||&nbsp;
  22.         <c:choose>
  23.             <c:when test=”${page.hasNextPage eq false}”>
  24.                 &nbsp;下页&gt&nbsp;尾页&gt&gt
  25.             </c:when>
  26.             <c:otherwise>
  27.                 <a href=”${pathurl}?&pageAction=next${urlParams}”>下一页&gt&nbsp;</a>&nbsp;
  28.                 <a href=”${pathurl}?pageAction=last${urlParams}” />末页&gt&gt</a>
  29.             </c:otherwise>
  30.         </c:choose>
  31.         &nbsp;
  32.         <SELECT name=”indexChange” id=”indexChange”
  33.             onchange=”getCurrentPage(this.value);”>
  34.             <c:forEach var=”index” begin=”1″ end=”${page.totalPage}” step=”1″>
  35.                 <option value=”${index}” ${page.currentPage eq index ? ”selected” : ”"}>
  36.                     第${index}页
  37.                 </option>
  38.             </c:forEach>
  39.         </SELECT>
  40.         &nbsp;
  41.         每页显示:<select name=”everyPage” id=”everyPage” onchange=”setEveryPage(this.value);”>
  42.                    <c:forEach var=”pageCount” begin=”5″ end=”${page.totalCount}” step=”5″>
  43.                         <option value=”${pageCount}” ${page.everyPage eq pageCount ? ”selected” : ”"}>
  44.                             ${pageCount}条
  45.                         </option>
  46.                     </c:forEach>
  47.                </select>
  48.     </td>
  49. </tr>
  50. <div style=’display: none’>
  51.     <a class=listlink id=”indexPageHref” href=’#'></a>
  52. </div>
  53. <script>
  54. function getCurrentPage(index){
  55.     var a = document.getElementById(“indexPageHref”);
  56.     a.href = ’${pathurl}?pageAction=gopage&currentPage=’+index+’${urlParams}’;
  57.     a.setAttribute(“onclick”,”);
  58.     a.click(“return false”);
  59. }
  60. function setEveryPage(everyPage){
  61.     var a = document.getElementById(“indexPageHref”);
  62.     var currentPage = document.getElementById(‘indexChange’).value;
  63.     a.href = ’${pathurl}?pageAction=setpage&everyPage=’+everyPage+’${urlParams}’;
  64.     a.setAttribute(“onclick”,”);
  65.     a.click(“return false”);
  66. }
  67. function sortPage(sortName){
  68.     var a = document.getElementById(“indexPageHref”);
  69.     a.href = ’${pathurl}?pageAction=sort&sortName=’+sortName+’${urlParams}’;
  70.     a.setAttribute(“onclick”,”);
  71.     a.click(“return false”);
  72. }
  73. </script>