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



    2 UserAction.java 

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



    3 UserDAOImpl.java 

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



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



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

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



    2 PageState.java 

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


    3 PageUtil.java 

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


    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> 
      74. 原地址是   http://liuzidong.iteye.com/blog/1042172
  • 相关阅读:
    xmgrace的配置
    redhat 的安装及grub livecd 的引导
    AutoDock 的安装及 virtual screening 的配置
    怎么查看redhat版本
    分子模拟软件schrodinger的安装
    Amber学习第八天:含有配体的蛋白分子动力学
    Amber 模拟蛋白流程
    Openbabel的安装
    Amber 的安装
    浅谈SQL Server 对于内存的管理
  • 原文地址:https://www.cnblogs.com/whtydn/p/6093417.html
Copyright © 2020-2023  润新知