一个struts+hibernate分页范例

一个struts+hibernate分页实例
前一段时间在做一个作业,用到分页,再网上看里许多例子,发现都很繁琐,于是自己写了一个分页静态类,很好用!因为全在同一个类里,直接调用不同的方法就可以得到不同的List<?>结果集,大家指教一下。

分页类:
package com.liufei.hibernate.domain;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/**
* 分页并按条件查询的操作类
*
* @author 刘飞
*
*/
public class PageUtil {

private static Configuration configuration;
private static SessionFactory sessionFactory;
private static Session session;

private static Class<?> clazz; // 为该类设置映射的实体类

private static DetachedCriteria detachedCriteria; //全局共享的<tt>DetachedCriteria</tt>对象

private static int indexPage = 1; // 当前页

private static boolean isHomePage ;
private static boolean isLastPage ;

private static int countPage; // 一共多少页
private static final int pageCount = 6; // 每页显示的记录条数
private static int allCounts; // 记录总数
public static List<?> listNeed; // List结果集

public static int[] indexs = new int[0] ; //分页索引数组

private static String queryCondition ;



/**
* 指定该类不可以被继承
*/
private PageUtil() {

}

static {
configuration = new Configuration().configure();
}

/**
* 打开<tt>SessionFactory</tt>对象
*/
public static void openSessionFactory() {
try {
sessionFactory = configuration.buildSessionFactory();
} catch (HibernateException sfe) {
sfe.printStackTrace();
}
}

/**
* 打开<tt>Session</tt>对象
*/
public static void openSession() {
try {
session = sessionFactory.openSession();
} catch (HibernateException se) {
se.printStackTrace();
}
}

/**
* 关闭当前<tt>SessionFactory</tt>对象
*/
public static void closeSessionFactory() {
if (sessionFactory.isClosed()) {
sessionFactory.close();
}
}

/**
* 关闭当前<tt>Session</tt>对象
*/
public static void closeSession() {
if (session.isOpen()) {
session.close();
}
}

/**
* 获取SessionFactory对象
*
* @return SessionFactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
* 获取Session对象
*
* @return Session
*/
public static Session getSession() {
return session;
}

/**
* 得到该类设置映射的实体类
*
* @return Class<?>
*/
public static Class<?> getClazz() {
return clazz;
}

/**
* 为该类设置映射的实体类
*
* @param clazz
*/
public static void setClazz(Class<?> clazz) {
PageUtil.clazz = clazz;
}

/**
* 获取查询条件
* @return String
*/
public static String getQueryCondition() {
return queryCondition;
}

/**
* 设置查询条件
* @param queryCondition
*/
public static void setQueryCondition(String queryCondition) {
PageUtil.queryCondition = queryCondition;
}
/**
* 将<tt>DetachedCriteria</tt>对象绑定到当前打开的<tt>Session</tt>
* 对象上,(可以使用add()方法在绑定前加入查询条件)
* 建立Session后,通过getExecutableCriteria(getSession())方法获取Criteria实例
* 在当前打开的Session对象关闭之后,DetachedCriteria对象依然存在,可以继续访问和操作 该方法依据具体的实体类对象为该类提供一个
* <tt>DetachedCriteria</tt>对象
*
* @param clazz
* @return List
*/
public static DetachedCriteria getDetachedCriteriaList() {
detachedCriteria = DetachedCriteria.forClass(getClazz());
return detachedCriteria;
}

/**
* 依据getDetachedCriteriaList(Class<?> clazz)方法所返回的<tt>DetachedCriteria</tt>
* 对象得到<tt>Criteria</tt>对象
*
* @return Criteria
*/
public static Criteria getCriteria() {
Criteria criteria = detachedCriteria.getExecutableCriteria(session);
criteria.setFirstResult((getIndexPage() - 1) * getPagecount()); // 设置当前页
criteria.setMaxResults(getPagecount()); // 设置当前页要显示的记录数
return criteria;
}

/**
* 获取当前页
*
* @return int
*/
public static int getIndexPage() {
return indexPage;
}

/**
* 设置当前页
*
* @param indexPage
*/
public static void setIndexPage(int indexPage) {
PageUtil.indexPage = indexPage;
}

/**
* 获取分页索引数组
* @return int[]
*/
public static int[] getIndexs() {
int[] index = new int[0] ;
for(int i = 0 ; i < getCountPage() ; i++ ){
index[i] = i + 1 ;
}
PageUtil.indexs = index;
return PageUtil.indexs;
}

/**
* 获取由getCriteria()方法返回的Criteria对象生成的List<?>结果集
*
* @return List<?>
*/
public static List<?> getListNeed() {
setListNeed();
return listNeed;
}

/**
* 由getCriteria()方法返回的Criteria对象获取List<?>结果集
*/
public static void setListNeed() {
List<?> listNeed;
listNeed = getCriteria().list();
PageUtil.listNeed = listNeed;
}


/**
* 设置上一页
*/
public static void setPreviouePage() {
int index = 1;
if(isHomePage()){
index = getIndexPage() - 1 ;
}else{
setIndexPage(1) ;
System.out.println("已经是首页了") ;
}

setIndexPage(index) ;
}


/**
* 设置下一页
*
* @param nextPage
*/
public static void setNextPage() {
int index = 0 ;
if(isLastPage()){
index = getIndexPage() + 1 ;
}else{
setIndexPage(getCountPage()) ;
System.out.println("已经是最后一页了") ;
}
setIndexPage(index) ;
}

/**
* 是否是首页
*
* @return boolean
*  true 表示是首页   false  表示不是首页
*/
public static boolean isHomePage() {
boolean HomePage = false;
if (getIndexPage() == 1){
HomePage = true ;
}
isHomePage = HomePage ;
return isHomePage;
}

/**
* 是否是最后一页
*
* @return boolean
* true 表示是最后一页 false  表示不是最后一页
*/
public static boolean isLastPage() {
boolean lastPage = false ;
if (getIndexPage() == getCountPage()){
lastPage = true ;
}
isLastPage = lastPage ;
return isLastPage;
}

/**
* 获取总页数
*
* @return int
*/
public static int getCountPage() {
int countPage = 1;
countPage = ((getAllCounts() / pageCount) + 1);
PageUtil.countPage = countPage;
return PageUtil.countPage;
}

/**
* 获取记录总数
*
* @return int
*/
public static int getAllCounts() {
int allCounts = 0;
Criteria criteria;
criteria = getSession().createCriteria(getClazz()) ;
allCounts = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
PageUtil.allCounts = allCounts;
return PageUtil.allCounts;
}

/**
* 设置首页
*
*/
public static void setHomePage() {
setIndexPage(1);
}

/**
* 设置尾页
*
* @param lastPage
*/
public static void setLastPage() {
setIndexPage(getCountPage()) ;
}

/**
* 每页显示的记录条数(常量)
*
* @return int
*/
public static int getPagecount() {
return pageCount;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PageUtil.openSessionFactory();
PageUtil.openSession();

PageUtil.setClazz(InsertDB.class);
PageUtil.getDetachedCriteriaList() ;
//setNextPage();
//setNextPage();
//setPreviouePage();
//setPreviouePage();
setHomePage() ;
//setLastPage() ;
List<?> list = PageUtil.getListNeed();
Iterator<?> iterator = list.iterator();
System.out
.println("验证查询************************************************");
System.out.println("主键编号" + "\t" + "姓名" + "\t" + "Email地址");
while (iterator.hasNext()) {
InsertDB user = (InsertDB) iterator.next();
System.out.println(user.getId() + "\t" + user.getName() + "\t" + user.getEmail());
}
System.out
.println("验证记录条数**********************************************");
System.out.println("总记录条数为:\t" + getAllCounts());
System.out
.println("验证页数***************************************************");

System.out.println("总页数为:\t" + getCountPage());
System.out
.println("验证是否首页***************************************************");
System.out.println(isHomePage()) ;
System.out
.println("验证是否最后一页***************************************************");
System.out.println(isLastPage()) ;
System.out
.println("验证当前页***************************************************");
System.out.println(getIndexPage()) ;
System.out
.println("验证分页数组***************************************************");
for(int i = 1 ; i <= getCountPage() ; i++){
System.out.println(i) ;
}
/*int[] indexget = PageUtil.getIndexs() ;
for(int i = 0 ; i < indexget.length ; i++){
System.out.println(indexget[i]) ;
}*/
PageUtil.closeSession() ;
PageUtil.closeSessionFactory() ;
}

}
Action:
package com.liufei.actions;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import org.hibernate.Query;

import com.liufei.hibernate.domain.HibernateUtil;
import com.liufei.hibernate.domain.InsertDB;
import com.liufei.hibernate.domain.PageUtil;
import com.opensymphony.xwork2.ActionSupport;

public class QueryDelete extends BaseAction {

/**
*
*/
private static final long serialVersionUID = 1L;
private String QueryID = "liufei" ;
private static List<?> cList ;



public String getQueryID() {
return QueryID;
}
public void setQueryID(String queryID) {
QueryID = queryID;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
PageUtil.openSessionFactory();
PageUtil.openSession();

PageUtil.setClazz(InsertDB.class);
PageUtil.getDetachedCriteriaList() ;
List<?> users = PageUtil.getListNeed() ;



return ActionSupport.SUCCESS;
}
public String select(){
HibernateUtil.openSessionFactory() ;
HibernateUtil.openSession() ;
String hql = "from InsertDB as user where user.name like :name" ;
// 调用session的获得数据列表方法,传递HQL查询语句
String value = "%" + getQueryID() + "%";
Query query = HibernateUtil.getSession().createQuery(hql);
query.setString("name",value);
cList = query.list() ;


//HttpSession session = session() ;
//session.setAttribute("listInfo", cList) ;
HibernateUtil.closeSession() ;
HibernateUtil.closeSessionFactory() ;

System.out.println("select");
return "selected" ;
}

public String delete(){

System.out.println("delete");
return "deleted" ;
}
public String next(){
PageUtil.setNextPage() ;
System.out.println("next");
return "next" ;
}
public String previous(){
PageUtil.setPreviouePage() ;
System.out.println("previous");
return "previous" ;
}
public String home(){
PageUtil.setHomePage() ;
System.out.println("home");
return "home" ;
}
public String last(){
PageUtil.setLastPage() ;

System.out.println("last");
return "last" ;
}

public static void main(String[] args){
QueryDelete test = new QueryDelete() ;

System.out.println(test.select()) ;

Iterator<?> iterat = cList.iterator() ;
while(iterat.hasNext()){
InsertDB insertdb = (InsertDB)iterat.next() ;
System.out.println(insertdb.getAddress()) ;
}
}
}
jsp页面:
<%@ page language="java" import="java.util.*,org.hibernate.Criteria,com.liufei.hibernate.domain.*,org.hibernate.Query,org.hibernate.SessionFactory,org.hibernate.cfg.Configuration,org.hibernate.Session" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>名片浏览与查询</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">

<link rel="stylesheet" type="text/css" href="styles.css">
<style type="text/css">
<!--
body {
background-color: #ccdddd
}

.containe {
background: #ccddef;
width: 70%;
height: 700px;
position: absolute;
left: 50%;
margin: 0px 0 0 -30%;
border-style: inset;
}

.containe .top {
margin: 1px;
background-color: #ddddff;
border: 1px outset #ccddee;
dashed: #111111;
border-style: outset;
text-align: right;
}
#time{
margin: 1px;
background-color: #ddddff;
border: 1px outset #ccddee;
dashed: #111111;
border-style: outset;
text-align: right;
}
#queryID{
margin: 1px;
background-color: #ddddee;
border: 1px outset #ccddee;
dashed: #111111;
border-style: outset;
text-align: right;
float:left ;
z-index : 0 ;
}

#show{
margin: 1px;
background-color: #dddffe;
border: 1px outset #ccddee;
dashed: #111111;
border-style: outset;
text-align: right;
z-index : 1 ;
}
#search{
background:url("images/search_but.gif") no-repeat;
width:80px;
height:25px;
}
#ttop{
text-align:center;
    padding-bottom:10px;
}
-->
</style>

  </head>
 
  <body>
  <%
java.util.Date now = new java.util.Date();
pageContext.setAttribute("now", now);

%>
   <div class="containe">
   <div id = "time"><s:label>本次操作时间是:</s:label><s:date name="#attr.now" nice="false" />
   <s:date name="unCarInsModificationInfo.createTime" format="yyyy-MM-dd" nice="false"/>
   </div>
   <p align="center">
<s:label>
<font size="8">名片浏览与查询</font>
</s:label>
</p>
<div class="top">
<s:form name = "sform" method="post" action = "QueryDelete.action">
<div id = "queryID">
<s:textfield name = "QueryID" label = "名片搜索(请键入姓名相关信息)"></s:textfield>
<s:submit id = "search" name = "action:select" type = "button" value = "" align = "right"></s:submit>
</div><hr/>
<table align="center">
<caption id = "ttop">查询的名片信息</caption>
<thead>
<tr>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">编号</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">姓名</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">性别</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">Email</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">涉足行业</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">手机号码</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">QQ号码</th>
<th align="center" valign="middle" width="50px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">MSN</th>
<th align="center" valign="middle" width="150px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">公司地址</th>
<th align="center" valign="middle" width="150px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">个人简介</th>
<th align="center" valign="middle" width="100px" height="5px" rowspan="1" colspan="1" bgColor="#808000" borderColor="#ff8040">操作选择</th>
</tr>
</thead>
<tbody>
<%
PageUtil.openSessionFactory();
PageUtil.openSession();

PageUtil.setClazz(InsertDB.class);
PageUtil.getDetachedCriteriaList() ;
List<?> users = PageUtil.getListNeed() ;
Iterator<?> iterator = users.iterator() ;
while(iterator.hasNext()){
InsertDB user = (InsertDB)iterator.next() ;

%>
<s:iterator status="status">
<tr <s:if test = "#status.odd">style="background-color:#c0c0d0"</s:if>>
<td align="center" valign="bottom" rowspan="1" colspan="1"><input type = "checkbox" name = "number" value = "<%=user.getName() %>"/><%=user.getId() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getName() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getSex() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getEmail() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getHangye() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getSellphone() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getQQnum() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getMSN() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getCompanyaddress() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1"><%=user.getInformation() %></td>
<td align="center" valign="bottom" borderColor="#000000" rowspan="1" colspan="1">

<a href='<s:url value="AlterInfo.jsp" >
<s:param name="num" value="#{ user.getId()}" /> 
<s:param name="insertdb.id" value="#{ user.id}"/></s:url>'> 
[修改名片] 
</a> 
</td>
</tr>
</s:iterator>
<%} %>
</tbody>
<tfoot align = "center"><tr><td align="center" valign="middle" colspan="12">
<a href = "home.action" >首页</a>
<a href = "previous.action" >上一页</a>
<a href = "next.action" >下一页</a>
<a href = "last.action" >尾页</a>

</td></tr></tfoot>

</table>
<center>
<s:submit id = "delete" name = "action:delete" type = "button" value = "移入回收站" align = "right"></s:submit>
</center>

</s:form>

</div>
</div>
  </body>
</html>
配置文件:
<action class="com.liufei.actions.QueryDelete" name="QueryDelete">
<result name="success">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="select" method = "select">
<result name="selected">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="delete" method = "delete">
<result name="deleted">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="next" method = "next">
<result name="next">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="previous" method = "previous">
<result name="previous">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="home" method = "home">
<result name="home">/QueryDeleteConn.jsp</result>
</action>

<action class="com.liufei.actions.QueryDelete" name="last" method = "last">
<result name="last">/QueryDeleteConn.jsp</result>
</action>