使用hibernate和struts2实现分页功能的示例

 更新时间:2017年01月04日 15:30:19   作者:xiaoluo501395377  
本篇文章主要介绍了使用hibernate和struts2实现分页功能,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

想着每天能学个新东西,今天准备了这个hibernate+struts2实现页面的分页功能,以下是源代码。

1.DAO层接口的设计,定义一个PersonDAO接口,里面声明了两个方法:

public interface PersonDAO
{
  public List<Person> queryByPage(String hql, int offset, int pageSize);
  
  public int getAllRowCount(String hql);
}

2.DAO层接口的实现类PersonDAOImpl类,将其两个方法实现出来:

public class PersonDAOImpl implements PersonDAO
{
  /**
   * 通过hql语句得到数据库中记录总数
   */
  @Override
  public int getAllRowCount(String hql)
  {
    Session session = HibernateUtil.openSession();
    Transaction tx = null;
    int allRows = 0;
    try
    {
      tx = session.beginTransaction();
      
      Query query = session.createQuery(hql);
      
      allRows = query.list().size();
      
      tx.commit();
      
    }
    catch (Exception e)
    {
      if(tx != null)
      {
        tx.rollback();
      }
      
      e.printStackTrace();
    }
    finally
    {
      HibernateUtil.closeSession(session);
    }
    
    return allRows;
  }
  /**
   * 使用hibernate提供的分页功能,得到分页显示的数据
   */
  @SuppressWarnings("unchecked")
  @Override
  public List<Person> queryByPage(String hql, int offset, int pageSize)
  {
    Session session = HibernateUtil.openSession();
    Transaction tx = null;
    List<Person> list = null;
    
    try
    {
      tx = session.beginTransaction();
      
      Query query = session.createQuery(hql).setFirstResult(offset).setMaxResults(pageSize);
      
      list = query.list();
      
      tx.commit();
      
    }
    catch (Exception e)
    {
      if(tx != null)
      {
        tx.rollback();
      }
      
      e.printStackTrace();
    }
    finally
    {
      HibernateUtil.closeSession(session);
    }
    
    
    return list;
  }
}

3.定义了一个PageBean(每一页所需要的内容都存放在这个PageBean里面),里面用来存放网页每一页显示的内容:

public class PageBean
{
  private List<Person> list; //通过hql从数据库分页查询出来的list集合
  
  private int allRows; //总记录数
  
  private int totalPage; //总页数
  
  private int currentPage; //当前页

  public List<Person> getList()
  {
    return list;
  }

  public void setList(List<Person> list)
  {
    this.list = list;
  }

  public int getAllRows()
  {
    return allRows;
  }

  public void setAllRows(int allRows)
  {
    this.allRows = allRows;
  }

  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;
  }
  
  /**
   * 得到总页数
   * @param pageSize 每页记录数
   * @param allRows 总记录数
   * @return 总页数
   */
  public int getTotalPages(int pageSize, int allRows)
  {
    int totalPage = (allRows % pageSize == 0)? (allRows / pageSize): (allRows / pageSize) + 1;
    
    return totalPage;
  }
  
  /**
   * 得到当前开始记录号
   * @param pageSize 每页记录数
   * @param currentPage 当前页
   * @return
   */
  public int getCurrentPageOffset(int pageSize, int currentPage)
  {
    int offset = pageSize * (currentPage - 1);
    
    return offset;
  }
  
  /**
   * 得到当前页, 如果为0 则开始第一页,否则为当前页
   * @param page
   * @return
   */
  public int getCurPage(int page)
  {
    int currentPage = (page == 0)? 1: page;
    
    return currentPage;
  }
  
}

4.Service层接口设计,定义一个PersonService接口,里面声明了一个方法,返回一个PageBean:

public interface PersonService
{
  public PageBean getPageBean(int pageSize, int page);
}

5.Service层接口实现类PersonServiceImpl类,实现唯一的方法:

public class PersonServiceImpl implements PersonService
{
  private PersonDAO personDAO = new PersonDAOImpl();
  
  /**
   * pageSize为每页显示的记录数
   * page为当前显示的网页
   */
  @Override
  public PageBean getPageBean(int pageSize, int page)
  {
    PageBean pageBean = new PageBean();
    
    String hql = "from Person";
    
    int allRows = personDAO.getAllRowCount(hql);
    
    int totalPage = pageBean.getTotalPages(pageSize, allRows);
    
    int currentPage = pageBean.getCurPage(page);
    
    int offset = pageBean.getCurrentPageOffset(pageSize, currentPage);
    
    List<Person> list = personDAO.queryByPage(hql, offset, pageSize);
    
    pageBean.setList(list);
    pageBean.setAllRows(allRows);
    pageBean.setCurrentPage(currentPage);
    pageBean.setTotalPage(totalPage);
    
    return pageBean;
  }
}

6.Action层设计,定义一个PersonAction:

public class PersonAction extends ActionSupport
{
  private PersonService personService = new PersonServiceImpl();
  
  private int page;
  
  public int getPage()
  {
    return page;
  }

  public void setPage(int page)
  {
    this.page = page;
  }

  @Override
  public String execute() throws Exception
  {
    //表示每页显示5条记录,page表示当前网页
    PageBean pageBean = personService.getPageBean(5, page);
    
    HttpServletRequest request = ServletActionContext.getRequest();
    
    request.setAttribute("pageBean", pageBean);
    
    return SUCCESS;
  }
}

7.辅助类设计,HibernateUtil:

public class HibernateUtil
{
  private static SessionFactory sessionFactory;
  
  static
  {
    sessionFactory = new Configuration().configure().buildSessionFactory();
  }
  
  public static Session openSession()
  {
    Session session = sessionFactory.openSession();
    
    return session;
  }
  
  public static void closeSession(Session session)
  {
    if(session != null)
    {
      session.close();
    }
  }
  
}

8.最后也就是分页页面显示pagePerson.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
 <head>
  <base href="<%=basePath%>">
  
  <title>My JSP 'pagePerson.jsp' starting page</title>
  
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">

  <script type="text/javascript">
  
    function validate()
    {
      var page = document.getElementsByName("page")[0].value;
        
      if(page > <s:property value="#request.pageBean.totalPage"/>)
      {
        alert("你输入的页数大于最大页数,页面将跳转到首页!");
        
        window.document.location.href = "personAction";
        
        return false;
      }
      
      return true;
    }
  
  </script>

 </head>
 
 <body>

  <h1><font color="blue">分页查询</font></h1><hr>
  
  <table border="1" align="center" bordercolor="yellow" width="50%">
  
    <tr>
      <th>序号</th>
      <th>姓名</th>
      <th>年龄</th>
    </tr>
  
  
  <s:iterator value="#request.pageBean.list" id="person">
  
    <tr>
      <th><s:property value="#person.id"/></th>
      <th><s:property value="#person.name"/></th>
      <th><s:property value="#person.age"/></th>    
    </tr>
  
  </s:iterator>
  
  </table>
  
  <center>
  
    <font size="5">共<font color="red"><s:property value="#request.pageBean.totalPage"/></font>页 </font>&nbsp;&nbsp;
    <font size="5">共<font color="red"><s:property value="#request.pageBean.allRows"/></font>条记录</font><br><br>
    
    <s:if test="#request.pageBean.currentPage == 1">
      首页&nbsp;&nbsp;&nbsp;上一页
    </s:if>
    
    <s:else>
      <a href="personAction.action">首页</a>
      &nbsp;&nbsp;&nbsp;
      <a href="personAction.action?page=<s:property value="#request.pageBean.currentPage - 1"/>">上一页</a>
    </s:else>
    
    <s:if test="#request.pageBean.currentPage != #request.pageBean.totalPage">
      <a href="personAction.action?page=<s:property value="#request.pageBean.currentPage + 1"/>">下一页</a>
      &nbsp;&nbsp;&nbsp;
      <a href="personAction.action?page=<s:property value="#request.pageBean.totalPage"/>">尾页</a>
    </s:if>
    
    <s:else>
      下一页&nbsp;&nbsp;&nbsp;尾页
    </s:else>
  
  </center><br>
  
  <center>
    
    <form action="personAction" onsubmit="return validate();">
      <font size="4">跳转至</font>
      <input type="text" size="2" name="page">页
      <input type="submit" value="跳转">
    </form>
    
  </center>
  
 </body>
</html>

至此,hibernate+struts2实现网页分页功能代码部分就完毕了,像hibernate与struts的配置文件就不列出来了,那些都不是重点!

页面效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • springboot jpa分库分表项目实现过程详解

    springboot jpa分库分表项目实现过程详解

    这篇文章主要介绍了springboot jpa分库分表项目实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Mybatis-Plus使用MetaObjectHandler实现自动填充实体对象字段

    Mybatis-Plus使用MetaObjectHandler实现自动填充实体对象字段

    在我们使用Mybatis-Plus时,一些简单的CRUD,你会发现好多表,许多字段是重复的,如果我们每次更新或者新增,都要手动赋值,那么会出现许多不必要的重复操作,所以本文介绍了Mybatis-Plus使用MetaObjectHandler实现自动填充实体对象字段,需要的朋友可以参考下
    2024-11-11
  • mybatis连接MySQL8出现的问题解决方法

    mybatis连接MySQL8出现的问题解决方法

    这篇文章主要介绍了mybatis连接MySQL8出现的问题解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • SpringBoot中使用Jsoup爬取网站数据的方法

    SpringBoot中使用Jsoup爬取网站数据的方法

    这篇文章主要介绍了SpringBoot中使用Jsoup爬取网站数据的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • SpringBoot解决跨域请求拦截问题代码实例

    SpringBoot解决跨域请求拦截问题代码实例

    这篇文章主要介绍了SpringBoot解决跨域请求拦截代码实例,在微服务开发中,一个系统包含多个微服务,会存在跨域请求的场景。 本文讲解SpringBoot解决跨域请求拦截的问题。,需要的朋友可以参考下
    2019-06-06
  • Java Springboot的目的你知道吗

    Java Springboot的目的你知道吗

    在本篇文章中小编给大家分析了Java中Spring Boot的优势以及相关知识点内容,兴趣的朋友们可以学习参考下,希望能够给你带来帮助
    2021-09-09
  • java自定义动态链接数据库示例

    java自定义动态链接数据库示例

    这篇文章主要介绍了java自定义动态链接数据库示例,需要的朋友可以参考下
    2014-02-02
  • ObjectInputStream 和 ObjectOutputStream 介绍_动力节点Java学院整理

    ObjectInputStream 和 ObjectOutputStream 介绍_动力节点Java学院整理

    ObjectInputStream 和 ObjectOutputStream 的作用是,对基本数据和对象进行序列化操作支持。本文给大家详细介绍了ObjectInputStream 和 ObjectOutputStream的相关知识,感兴趣的朋友一起学习吧
    2017-05-05
  • SpringBoot发送html邮箱验证码功能

    SpringBoot发送html邮箱验证码功能

    这篇文章主要介绍了SpringBoot发送html邮箱验证码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • 一篇文章带你了解Java方法的使用

    一篇文章带你了解Java方法的使用

    这篇文章主要给大家介绍了关于Java中方法使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08

最新评论