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

时间:2022-11-01 11:51:12

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

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

?
1
2
3
4
5
6
public interface PersonDAO
{
  public List<Person> queryByPage(String hql, int offset, int pageSize);
  
  public int getAllRowCount(String hql);
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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里面),里面用来存放网页每一页显示的内容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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:

?
1
2
3
4
public interface PersonService
{
  public PageBean getPageBean(int pageSize, int page);
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<%@ 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的配置文件就不列出来了,那些都不是重点!

页面效果如下:

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

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

原文链接:http://www.cnblogs.com/xiaoluo501395377/archive/2012/10/18/2730073.html