Page的实现 HibernatePage.java 和以前一样
package cn.loen.platform.util.page;
import java.util.List;
public class HibernatePageimplements Page {
private List elements;
private int pageSize;
private int pageNumber;
private int totalElements;
/**
* 构建HibernatePage对象,完成数据的分页处理
*
* @param elements
* List数据源
* @param totalElements
* 记录总数
* @param pageNumber
* 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。
* 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。
* 这两种情况将重新更改当前页的页码为最后一页编码。
* @param pageSize
* 每一页显示的条目数
*/
public HibernatePage(List elements, int totalElements, int pageNumber,
int pageSize) {
this.elements = elements;
this.totalElements = totalElements;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
if (this.pageNumber == Integer.MAX_VALUE ||
this.pageNumber > getLastPageNumber()) {
this.pageNumber = getLastPageNumber();
}
}
public boolean isFirstPage() {
return getThisPageNumber() == 1;
}
public boolean isLastPage() {
return getThisPageNumber() >= getLastPageNumber();
}
public boolean hasNextPage() {
return getLastPageNumber() > getThisPageNumber();
}
public boolean hasPreviousPage() {
return getThisPageNumber() > 1;
}
public int getLastPageNumber() {
return totalElements % this.pageSize == 0 ? totalElements
/ this.pageSize : totalElements / this.pageSize + 1;
}
public List getThisPageElements() {
return elements;
}
public int getTotalNumberOfElements() {
return totalElements;
}
public int getThisPageFirstElementNumber() {
return (getThisPageNumber() - 1) * getPageSize() + 1;
}
public int getThisPageLastElementNumber() {
int fullPage = getThisPageFirstElementNumber() + getPageSize() - 1;
return getTotalNumberOfElements() < fullPage ? getTotalNumberOfElements()
: fullPage;
}
public int getNextPageNumber() {
int nextPage = getThisPageNumber() + 1;
return nextPage < getLastPageNumber() ? nextPage : getLastPageNumber();
}
public int getPreviousPageNumber() {
int previousPage = getThisPageNumber() - 1;
return 1 < previousPage ? previousPage : 1;
}
public int getPageSize() {
return pageSize;
}
public int getThisPageNumber() {
return pageNumber;
}
public void setThisPageElements(List ls) {
elements = ls;
}
}
关键 QueryHandler.java 查询处理用于Hibernate查询
package cn.loen.platform.util.query;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import cn.loen.platform.util.page.HibernatePage;
import cn.loen.platform.util.page.Page;
import cn.loen.platform.common.BaseDAO;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
/**
*
* <p>Title: www.loen.cn</p>
*
* <p>Description: v1.0</p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: loen</p>
*
* @author bright([email protected])
* @version 1.0
*/
public class QueryHandler {
private static QueryHandler instance = new QueryHandler();
public static QueryHandler instance() {
return instance;
}
private QueryHandler() {
}
/**
* 得到记录总数
* @param hql String
* @param values Object[]
* @return int
* @throws HibernateException
*/
public int getTotalCountS(String hql, Object[] values) throws
HibernateException {
Integer count = new Integer(0);
/**
* 去掉排序
*/
int sql_orderby = hql.indexOf("order by");
if(sql_orderby>0)
hql = hql.substring(0,sql_orderby);
/**
* 去掉条件
*/
hql=(hql.split("from"))[1];
StringBuffer countStr = new StringBuffer("select count(*) from");
countStr.append(hql);
Session session = null;
List list = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(countStr.toString());
for (int i = 0; i < values.length; i++) {
int z = i;
query.setParameter(z=z==0?0:i*2, values[i]);
query.setParameter(z=z==0?1:i*2+1, values[i]);
/*第二版 不用管查询参数是否为null 把所有的查询条件都写到String hql语句中
注意要把所有的查询条件的null转化为' '(空字符串);
例如:String hql = "select * from Table as t where (t.name=? or ' '=?) and (t.country=? or ' '=?)";
*/
}
list = query.list();
if (!list.isEmpty())
count = (Integer) list.get(0);
return count.intValue();
} finally {
session.close();
}
}
/**
* @deprecated
* @param hql String
* @param values Object[]
* @return int
* @throws HibernateException
*/
public int getTotalCount(String hql, Object[] values) throws
HibernateException {
Integer count = new Integer(0);
/**
* 去掉排序
*/
int sql_orderby = hql.indexOf("order by");
if(sql_orderby>0)
hql = hql.substring(0,sql_orderby);
/**
* 去掉条件
*/
hql=(hql.split("from"))[1];
StringBuffer countStr = new StringBuffer("select count(*) from");
countStr.append(hql);
Session session = null;
List list = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(countStr.toString());
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);//第一版 需要对hql的查询参数进行判断是否存在 如果存在 就在String hql 后面加上" and Value=?"
}
list = query.list();
if (!list.isEmpty())
count = (Integer) list.get(0);
return count.intValue();
} finally {
session.close();
}
}
public int getTotalCountMap(String hql, Map map) throws
HibernateException {
Integer count = new Integer(0);
/**
* 去掉排序
*/
if(StringUtils.contains(hql,"order by"))
hql = StringUtils.substringBefore(hql,"order by");
/**
* 去掉fetch
*/
if(StringUtils.contains(hql,"fetch"))
hql = StringUtils.replace(hql,"fetch","");
/**
* 去掉条件
*/
hql = StringUtils.substringAfter(hql,"from");
StringBuffer countStr = new StringBuffer("select count(*) from");
countStr.append(hql);
Session session = null;
List list = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(countStr.toString());
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext())
{
String key = (String)it.next();
Object value = map.get(key);
query.setParameter(key,value);
}
/*由于第二版有个参数的顺序问题 就是页面传递过来的list或者String[]的顺序必须和hql的查询条件顺序一致 故利用Hibernate的查询改写成map
例如:String hql = "select * from Table as t where (t.name=:name or ' '=:name) and (t.country=:country or ' '=:country)";
页面传递进来只需要传递一个Map map = new Hashmap();
map.put("country",value0);map.put("name",value1);
*/
list = query.list();
if (!list.isEmpty())
count = (Integer) list.get(0);
return count.intValue();
} finally {
session.close();
}
}
/**
* 按页数得到需要记录数
* @param hql String
* @param values Object[]
* @param pageNo int
* @param pageSize int
* @return List
* @throws HibernateException
*/
public List queryS(String hql, Object[] values, int pageNo, int pageSize) throws
HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
for (int i = 0; i < values.length; i++) {
int z = i;
query.setParameter(z=z==0?0:i*2, values[i]);
query.setParameter(z=z==0?1:i*2+1, values[i]);
}
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
return query.list();
} finally {
session.close();
}
}
/**
* @deprecated
* @param hql String
* @param values Object[]
* @param pageNo int
* @param pageSize int
* @return List
* @throws HibernateException
*/
public List query(String hql, Object[] values, int pageNo, int pageSize) throws
HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
for (int i = 0; i < values.length; i++) {
int z = i;
query.setParameter(i, values[i]);
}
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
return query.list();
} finally {
session.close();
}
}
public List queryMap(String hql, Map map, int pageNo, int pageSize) throws
HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext())
{
String key = (String)it.next();
Object value = map.get(key);
query.setParameter(key,value);
}
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
return query.list();
} finally {
session.close();
}
}
/**
* 取得全部记录
* @param hql String
* @param values Object[]
* @return List
* @throws HibernateException
*/
public List queryAll(String hql, Object[] values) throws HibernateException {
List list = null;
Session session = null;
try {
session = BaseDAO.getSession();
Query query = session.createQuery(hql);
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
return query.list();
} finally {
session.close();
}
}
public Page queryByPage(int pageNumber, int pageSize, Object[] values,
String hql) {
Page page = null;
try {
int total = QueryHandler.instance().getTotalCount(hql, values);
List querylist = QueryHandler.instance().query(hql, values,
pageNumber, pageSize);
page = new HibernatePage(querylist, total, pageNumber, pageSize);
} catch (Exception e) {
e.printStackTrace();
}
return page;
}
public Page queryByPageS(int pageNumber, int pageSize, Object[] values,
String hql) {
Page page = null;
try {
int total = QueryHandler.instance().getTotalCountS(hql, values);
List querylist = QueryHandler.instance().queryS(hql, values,
pageNumber, pageSize);
page = new HibernatePage(querylist, total, pageNumber, pageSize);
} catch (Exception e) {
e.printStackTrace();
}
return page;
}
public Page queryByPageMap(int pageNumber, int pageSize, Map map,
String hql) {
Page page = null;
try {
int total = QueryHandler.instance().getTotalCountMap(hql, map);
List querylist = QueryHandler.instance().queryMap(hql, map,
pageNumber, pageSize);
page = new HibernatePage(querylist, total, pageNumber, pageSize);
} catch (Exception e) {
e.printStackTrace();
}
return page;
}
}
Services 调用 XXServices.java
public XXServices{
public Page queryCourseByPage(int pageNum, int pageSize, Map map) throws BusinessException {
String hql = "from Course as c where ((:provincecode='') or (c.provincecode=:provincecode)) and ((:citycode='') or (c.citycode=:citycode)) and ((:recommendernum='') or (c.recommendernum=:recommendernum)) and ((:isdisable='') or (c.isdisable=:isdisable)) and ((:coursename = '') or (c.coursename like '%' || :coursename || '%'))";
map.put("isdisable","Y");
Page page = null;
try {
page = QueryHandler.instance().queryByPageMap(pageNum, pageSize,
map,
hql);
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(e.getMessage());
}
return page;
}
}
Servlet调用: CourseAction.java
public class CourseAction extends DispatchAction {
public ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
BusinessException {
CourseActionForm courseForm = (CourseActionForm) form;
String pageNumStr = request.getParameter("pageNumber");
//可以把页树也封装到formBean中,页面放一个隐藏字段存放page
if (pageNumStr == null) {
pageNumStr = "1";
}
pageNumber = Integer.parseInt(pageNumStr);
Map map = new HashMap();
map.put("provincecode",courseForm.getProvincecode());
map.put("citycode",courseForm.getCitycode());
map.put("recommendernum",courseForm.getRecommendernum());
map.put("coursename",courseForm.getCoursename());
Page page = this.getICourseService().queryCourseByPage(pageNumber,pageSize,map);
request.setAttribute("Page",page);
String path = request.getRequestURI();
request.setAttribute("myPageURL", path+"?method=list");
request.setAttribute("formName","courseForm");
//把当前action路径和form的名称传到页面 用于分页跳转
//主要目地是为了分离PageBar.jsp 也就是分页跳转导航条 便于通用
return mapping.findForward("success"); //程序出口 返回到页面
}
private int pageNumber = 1;
private int pageSize = 5;
//取得service实例
private ICourseService getICourseService() {
return (ICourseService) ProxyService.
getBusinessService(
"CourseService");
}
}
页面: courselist.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.util.*"%>
<%@ page import="cn.loen.platform.util.page.Page"%>
<%
Page myPage = (Page)request.getAttribute("Page");
int lastPageNumber = 0;//总页数
int nextPageNumber = 0;//下页
int pageSize = 0;//每页记录数
int previoutPageNumber = 0;//上页
List orderlist = new ArrayList();//数据
int firstElement = 0;//当前第一条
int lastElement = 0;//当前最后一条
int pageNum = 0;//当前第几页
int totalElement = 0;//总记录数
if (myPage != null){
lastPageNumber = myPage.getLastPageNumber();//总页数
nextPageNumber = myPage.getNextPageNumber();//下页
pageSize = myPage.getPageSize();//每页记录数
previoutPageNumber = myPage.getPreviousPageNumber();//上页
orderlist = myPage.getThisPageElements();//数据
firstElement = myPage.getThisPageFirstElementNumber();//当前第一条
lastElement = myPage.getThisPageLastElementNumber();//当前最后一条
pageNum = myPage.getThisPageNumber();//当前第几页
totalElement = myPage.getTotalNumberOfElements();//总记录数
//这里就是HibernatePage.java与Page.java的用处
//page = new HibernatePage(querylist, total, pageNumber, pageSize); 把list,总数量,当前页数,每页数量 都封装到page中
}
String pageURL = (String)request.getAttribute("myPageURL");
String formName = (String)request.getAttribute("formName");
%>
<table border="0" cellspacing="0" cellpadding="0" width="80%" >
<tr>
<td>共<%=totalElement%>条/每页<%=pageSize%>条 第<%=pageNum%>页/共<%=lastPageNumber%>页</td>
<td>
<div align="right">[<a href="javascript:gotoPage(1)">首页</a>][<a href="javascript:gotoPage(<%=previoutPageNumber%>)">上一页</a>][<a href="javascript:gotoPage(<%=nextPageNumber%>)">下一页</a>][<a href="javascript:gotoPage(<%=lastPageNumber%>)">末页</a>]
转第
<select name="jump" onchange="jumpPage(this)">
<%for (int i = 1; i <= lastPageNumber; i++) {
if (i == pageNum) {%>
<option selected value="<%=i%>"><%=i%></option>
<%}
else{%>
<option value="<%=i%>"><%=i%></option>
<%}
}%>
</select>
页
</div></td>
</tr>
</table>
<SCRIPT LANGUAGE="JavaScript" type="">
function jumpPage(selObj){
document.forms.<%=formName%>.action="<%=pageURL%>&pageNumber="+selObj.options[selObj.selectedIndex].value;
document.forms.<%=formName%>.submit();
}
function gotoPage(pageNumber){
document.forms.<%=formName%>.action="<%=pageURL%>&pageNumber="+pageNumber;
document.forms.<%=formName%>.submit();
}
</SCRIPT>
注意:在formBean的reset方法中要把查询条件的null转化为" " 或者在Action Servlet中转换
public class CourseActionForm extends ValidatorForm {
private String address;
private String citycode;
private String courseid;
private String coursename;
private String designer;
private String fax;
private String holenumber;
private String provincecode;
private String tel;
private String typegreens;
private String zipcode;
private String remarkxml;
private FormFile smallpicup;
private String smallpic;
private String recommendernum;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public void setTypegreens(String typegreens) {
this.typegreens = typegreens;
}
public void setTel(String tel) {
this.tel = tel;
}
public void setProvincecode(String provincecode) {
this.provincecode = provincecode;
}
public void setHolenumber(String holenumber) {
this.holenumber = holenumber;
}
public void setFax(String fax) {
this.fax = fax;
}
public void setDesigner(String designer) {
this.designer = designer;
}
public void setCoursename(String coursename) {
this.coursename = coursename;
}
public void setCourseid(String courseid) {
this.courseid = courseid;
}
public void setCitycode(String citycode) {
this.citycode = citycode;
}
public void setRemarkxml(String remarkxml) {
this.remarkxml = remarkxml;
}
public void setSmallpicup(FormFile smallpicup) {
this.smallpicup = smallpicup;
}
public void setSmallpic(String smallpic) {
this.smallpic = smallpic;
}
public void setRecommendernum(String recommendernum) {
this.recommendernum = recommendernum;
}
public String getCitycode() {
return citycode;
}
public String getCourseid() {
return courseid;
}
public String getCoursename() {
return coursename;
}
public String getDesigner() {
return designer;
}
public String getFax() {
return fax;
}
public String getHolenumber() {
return holenumber;
}
public String getProvincecode() {
return provincecode;
}
public String getTel() {
return tel;
}
public String getTypegreens() {
return typegreens;
}
public String getZipcode() {
return zipcode;
}
public String getRemarkxml() {
return remarkxml;
}
public FormFile getSmallpicup() {
return smallpicup;
}
public String getSmallpic() {
return smallpic;
}
public String getRecommendernum() {
return recommendernum;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
String parameter = actionMapping.getParameter();
String paramValue = httpServletRequest.getParameter(parameter);
parameter = httpServletRequest.getParameter("method");
if (paramValue.equals("save") || paramValue.equals("update")) {
ActionErrors errors = super.validate(actionMapping,
httpServletRequest);
return errors;
//如果你希望用户必须输入一个条件才返回相应的记录集 要不就返回null 你可以在这里进行客户端控制
} else {
return null;
}
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
this.provincecode=this.provincecode==null?"":this.provincecode;
this.citycode=this.citycode==null?"":this.citycode;
this.recommendernum=this.recommendernum==null?"":this.recommendernum;
this.coursename=this.coursename==null?"":this.coursename;
//如果是Integer对象 就转化为0 与struts机制一样 hql也是 :xx=0
//如果你希望用户必须输入一个条件才返回相应的记录集 要不就返回null 你可以在这里进行服务端控制或者servlet控制(servlet控制更有效率)
}
}
以上就是完成的分页例子
大家只需要2个地方自己写 1:hql查询语句 2:Map 的查询参数