ssh实现分页很简单,效果如图:,

java 分页显示总页数 java分页实现_Java仿京东分页效果实现

下面是分页源代码:直接拷贝到项目中即可使用:

在页面中的一个超链接进入分页页面:<a href="page_getPersonForPage.action?page=1">进入分页</a>

1、首先定义了一个PageBean.java用来存放分页相关的变量,总记录数,当前页,是否为第一页,是否为最后一页,计算总页数等变量,

/**
  * author:lez
  */
 package com.testssh.entity;
 import java.util.List;
 /**
  * @author LEZ
  *2015年6月12日
  */
 public class PageBean {
private List list;        //要返回的某一页的记录列表
private int allRow;         //总记录数
private int totalPage;        //总页数
private int currentPage;    //当前页
private int pageSize;        //每页记录数 
     private boolean isFirstPage;    //是否为第一页
private boolean isLastPage;        //是否为最后一页
private boolean hasPreviousPage;    //是否有前一页
private boolean hasNextPage;        //是否有下一页
public List getList() {
  return list;
}
public void setList(List list) {
  this.list = list;
}
public int getAllRow() {
  return allRow;
}
public void setAllRow(int allRow) {
  this.allRow = allRow;
}
public int getTotalPage() {
  return totalPage;
}
public void setTotalPage(int totalPage) {
  this.totalPage = totalPage;
}
public int getCurrentPage() {
  return currentPage;
}
public void setCurrentPage(int currentPage) {
  this.currentPage = currentPage;
}
public int getPageSize() {
  return pageSize;
}
public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
}
/**
 * 初始化分页信息
 */
public void init(){
   this.isFirstPage = isFirstPage();
   this.isLastPage = isLastPage();
   this.hasPreviousPage = isHasPreviousPage();
   this.hasNextPage = isHasNextPage();
 }
/**
 * 以下判断页的信息,只需getter方法(is方法)即可
 * @return
 */
public boolean isFirstPage() {
   return currentPage == 1;    // 如是当前页是第1页
 }
public boolean isLastPage() {
   return currentPage == totalPage;    //如果当前页是最后一页
}
public boolean isHasPreviousPage() {
   return currentPage != 1;        //只要当前页不是第1页
}
public boolean isHasNextPage() {
   return currentPage != totalPage;    //只要当前页不是最后1页
}
/**
 * 计算总页数,静态方法,供外部直接通过类名调用
 * @param pageSize 每页记录数
 * @param allRow 总记录数
 * @return 总页数
 */
public static int countTotalPage(final int pageSize,final int allRow){
   int totalPage = allRow % pageSize == 0 ? allRow/pageSize : allRow/pageSize+1;
   return totalPage;
 }
/**
  * 计算当前页开始记录
  * @param pageSize 每页记录数
  * @param currentPage 当前第几页
  * @return 当前页开始记录号
  */
public static int countOffset(final int pageSize,final int currentPage){
   final int offset = pageSize*(currentPage-1);
   return offset;
}
/**
 * 计算当前页,若为0或者请求的URL中没有"?page=",则用1代替
 * @param page 传入的参数(可能为空,即0,则返回1)
 * @return 当前页
 */
public static int countCurrentPage(int page){
   final int curPage = (page==0?1:page);
   return curPage;
}
 }

2、分页用到的PageAction.java

/**
  * author:lez
  */
 package com.testssh.action;


 import java.util.List;
 import com.opensymphony.xwork2.ActionContext;
 import com.opensymphony.xwork2.ActionSupport;
 import com.opensymphony.xwork2.ModelDriven;
 import com.testssh.entity.PageBean;
 import com.testssh.entity.Person;
 import com.testssh.service.PageService;
 /**
  * @author LEZ
  * 2015年7月9日
  */
 public class PageAction extends ActionSupport implements ModelDriven<Person>{
/**
* 
*/
private static final long serialVersionUID = 9204107205966488044L;
private PageBean pageBean;    //包含分布信息的bean
private int page;    //第几页
private PageService pageService;
private Person person=new Person();
public PageService getPageService() {
return pageService;
}
public void setPageService(PageService pageService) {
this.pageService = pageService;
}

public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
    /**
     * author:lez
     * data:2015-7-10 
     * 分页的主要action方法
     */
    public String getPersonForPage(){
 this.pageBean = pageService.getPersonForPage(page);
  List<Person> lists=pageBean.getList();
  System.out.println("lists="+lists);
  ActionContext.getContext().put("lists",lists);
  ActionContext.getContext().put("pageBean",pageBean);
  return "nba";
    }
    public Person getPerson() {
return person;
 }
 public void setPerson(Person person) {
this.person = person;
System.out.println("person==="+person);
 }
 public String save(){
 System.out.println("person="+person);
 pageService.save(person);
     return "index";
    }
 @Override
 public Person getModel() {
return person;
 }
 }

3、struts.xml中分页用到的

<action name="page_*" class="com.testssh.action.PageAction" method="{1}">
            <result name="nba">/NBA.jsp</result>
            <result name="index">/index.jsp</result>
 </action>

4、分页用到的dao,PageDao.java

package com.testssh.dao;

 import java.util.List;
 import com.testssh.entity.Person;

 public interface PageDao {
   public int getAllRowCount(String hql);
   public List<Person> queryForPageByUpload(String hql, int offset, int length);
 }

5、分页用到的dao实现类

package com.testssh.dao.Impl;

 import java.util.List;
 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import com.testssh.dao.PageDao;
 import com.testssh.entity.Person;

 public class PageDaoImpl implements PageDao{
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
@Override
public int getAllRowCount(String hql) {
System.out.println("hql="+hql);
return getSession().createQuery(hql).list().size();
}

@Override
public List<Person> queryForPageByUpload(String hql, int offset, int length) {
Query query=(Query) getSession().createQuery("FROM Person");
query.setFirstResult(offset).setMaxResults(length);
return query.list();
}
 }

6、分页用到的service

package com.testssh.service;

 import com.testssh.entity.PageBean;
 import com.testssh.entity.Person;


 public interface PageService {
   public PageBean getPersonForPage(int page);

 public void save(Person person);
 }

7、service的实现类

package com.testssh.service.Impl;


 import java.util.List;


 import org.hibernate.Session;
 import org.hibernate.SessionFactory;


 import com.testssh.dao.PageDao;
 import com.testssh.entity.PageBean;
 import com.testssh.entity.Person;
 import com.testssh.service.PageService;
 /**
  * 分页相关service实现类
  * @author lez
  * 2015-7-10
  *
  */
 public class PageServiceImpl implements PageService{
private SessionFactory sessionFactory;//注入sessionFactory
private PageDao pageDao;              //注入PageDao
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public PageDao getPageDao() {
return pageDao;
}
public void setPageDao(PageDao pageDao) {
this.pageDao = pageDao;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession(){     //获取session
return sessionFactory.getCurrentSession();
}
/**
* 分页主要方法并把获取到的信息保存到PageBean中
*/
@Override
public PageBean getPersonForPage(int page) {
   String hql = "FROM Person";        //查询语句
   int allRow = pageDao.getAllRowCount(hql);    //总记录数
   System.out.println("allRow="+allRow);
   int totalPage = PageBean.countTotalPage(3,allRow);    //总页数
   final int offset = PageBean.countOffset(3,page);    //当前页开始记录
   final int length = 3;    //每页记录数
   final int currentPage = PageBean.countCurrentPage(page);
   List<Person> list = pageDao.queryForPageByUpload(hql,offset,length);        //"一页"的记录
   //把分页信息保存到Bean中
   PageBean pageBean = new PageBean();
   pageBean.setPageSize(3);    
   pageBean.setCurrentPage(currentPage);
   pageBean.setAllRow(allRow);
   pageBean.setTotalPage(totalPage);
   pageBean.setList(list);
   pageBean.init();
   return pageBean;
}
@Override
public void save(Person person) {
         getSession().save(person); 
}


 }

8、最后是页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 <%@ taglib prefix="s" uri="/struts-tags" %>
 <%
 String path = request.getContextPath();
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>NBA超级球星名单</title>
     <link href="bootstrap-3.3.4-dist/css/bootstrap.min.css" rel="stylesheet">
     <script src="jquery/jquery-1.9.1.js"></script>
     <script src="bootstrap-3.3.4-dist/js/bootstrap.min.js"></script>
     <!-- 这个css样式是用来控制分页代码的样式 -->
     <style type="text/css">
      a.div{border:1px solid;border-color:#CDDBE8;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;padding:6px 6px 6px 6px;color:black;text-decoration:none;}
      a.div:link{color:#000000;text-decoration:none;} 
      a.div:visited {color:#000000;background:#E6E6E6;text-decoration:none;} 
      a.div:hover {color:#000000;background:#E6E6E6;text-decoration:none;} 
      a.div:active {color:#FFFFFF;border:1px solid #25C6FD;text-decoration:none;} 
      a.count{border:1px solid;border-color:#CDDBE8;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;padding:6px 8px 6px 8px;color:black;text-decoration:none;}
      a.count:link{color:#000000;text-decoration:none;} 
      a.count:visited {color:#000000;background:#E6E6E6;text-decoration:none;} 
      a.count:hover {color:#000000;background:#E6E6E6;text-decoration:none;} 
      a.count:active {color:#FFFFFF;border:1px solid #25C6FD;text-decoration:none;} 
     </style>
     <!-- 这段js代码用来控制当前页页码的颜色和其他页码颜色的不一样, -->
     <script type="text/javascript">
       $(function(){
    
  //鼠标悬停在分页按钮上,按钮的颜色会变成蓝色
    
  $("a[class='count']").hover(function(){
    
  $(this).css("background","#005AA0");
    
  });
    
  //鼠标离开分页按钮,则按钮的颜色恢复为原来的默认颜色
    
  $("a[class='count']").mouseout(function(){
    
  $(this).css("background","#ffffff");
    
  });
    
  //当前页的页码为红色
    
  $("a[class='count']").each(function(){
    
  var current=$(this).text();
    
  var page=$("#currentPage").val();
    
      if(current==page){
    
    
   $(this).css("border","0");
    
    
   $(this).css({"color":"red"});
    
      } 
    
            });
    
});
     </script>
   </head>
   <body>
     <table class="table table-hover">
       <thead>
          <tr>
           <th>名字</th><th>所属球队</th><th>年龄</th><th>位置</th><th>身价</th>
          </tr>
  </thead>
  <tbody>
          <s:iterator value="#lists">  <!-- 遍历的方式显示查询到的数据 -->
           <tr>
 <td>${name}</td>
 <td>${team}</td>
 <td>${age}</td>
 <td>${position}</td>
 <td>${worth}</td>
  </tr>  
    </s:iterator>
        </tbody>
      </table>
       <!--以下为分页代码。。。。 存放当前页码数 -->
      <input type="hidden" id="currentPage" value="${pageBean.currentPage}">
      <div style="margin-left:430px;margin-bottom:0px;">
         <!-- 判断当前页是否位1,如果不为1则显示上一页, -->
         <s:if test="%{pageBean.currentPage != 1}">
             <a class="div" href="page_getPersonForPage.action?page=${pageBean.currentPage-1}">
               <span class="glyphicon glyphicon-hand-left"></span>上一页
             </a>
         </s:if>
         <!-- 如果页码数大于4,则判断在上一页后边显示三个点 -->
         <s:if test="pageBean.currentPage>4">
             <span>...</span>
         </s:if>
         <s:if test="pageBean.allRow/3>5">
           <!-- 存放当前页码数 -->
           <input type="hidden" id="currentPage1" value="${pageBean.currentPage}">
               <!-- 这个判断让页面动起来 -->
           <s:if test="pageBean.currentPage>4">
                 <a class="count" href="page_getPersonForPage.action?page=${pageBean.currentPage-2}">${pageBean.currentPage-2}</a>
                 <a class="count" href="page_getPersonForPage.action?page=${pageBean.currentPage-1}">${pageBean.currentPage-1}</a>
                 <a class="count" href="page_getPersonForPage.action?page=${pageBean.currentPage}">${pageBean.currentPage}</a>
                  <!-- 判断页码数到最后了就不要显示省略点了 -->
               <s:if test="(pageBean.currentPage+2)<=(pageBean.allRow/3)">
           <a class="count" href="page_getPersonForPage.action?page=${pageBean.currentPage+1}">${pageBean.currentPage+1}</a>
           <a class="count" href="page_getPersonForPage.action?page=${pageBean.currentPage+2}">${pageBean.currentPage+2}</a>
               </s:if>
           </s:if>
             <!-- 如果页面没有大于5那就先用写死的页码 -->
           <s:else>
            <a class="count" href="page_getPersonForPage.action?page=1">1</a>
            <a class="count" href="page_getPersonForPage.action?page=2">2</a>
            <a class="count" href="page_getPersonForPage.action?page=3">3</a>
            <a class="count" href="page_getPersonForPage.action?page=4">4</a>
            <a class="count" href="page_getPersonForPage.action?page=5">5</a>
           </s:else>
           <!-- 如果当前页加上2还大于总页数,那么三个点就显示,否则不显示 -->
           <s:if test="(pageBean.currentPage+2)<(pageBean.allRow/3)">
             <span>...</span>
           </s:if>
         </s:if>
         <s:else>
         <!-- 当页码数小于5时,用bean标签实现页面的遍历 -->
         <s:bean name="org.apache.struts2.util.Counter" id="counter">
           <s:param name="first" value="1" />
           <s:param name="last" value="pageBean.totalPage" />
           <s:iterator>
               <a class="count" href="page_getPersonForPage.action?page=<s:property/>"><s:property/></a>
           </s:iterator>
         </s:bean>
  
         </s:else> 
         <s:if test="%{pageBean.currentPage != pageBean.totalPage}">
             <a class="div" href="page_getPersonForPage.action?page=${pageBean.currentPage+1}">
                                         下一页<span class="glyphicon glyphicon-hand-right" title="fen"></span>
             </a>
         </s:if>
         <span>共<s:property value="pageBean.totalPage"/>页</span>   
          <s:form action="page_getPersonForPage.action" theme="simple" style="display: inline;">
            <span>跳转到第<s:textfield name="page" style="width:20px;" value="1"></s:textfield>页</span>
            <s:submit value="确定"></s:submit>
          </s:form>
      </div>
      <!-- -----分页结束----- -->
   </body>
 </html>