package com.fwxx.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class PageDAO extends HibernateDaoSupport{
private String hql;
private List args;
//分页方法
public List queryPage(final int begin,final int max){
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
Query query= session.createQuery(hql);
for (int i = 0; i < args.size(); i++) {
query.setParameter(i, args.get(i));
}
return query.setFirstResult(begin)
.setMaxResults(max).list();
}
});
}
public int getCount(){
return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
//有order by的 自己去截取掉 //
Query query= session.createQuery("select count(*) "+hql);
for (int i = 0; i < args.size(); i++) {
query.setParameter(i, args.get(i));
}
return query.uniqueResult();
}
});
}
public void splitPage(HttpServletRequest request,String hql){
this.splitPage(request, hql, new ArrayList());
}
public void splitPage(HttpServletRequest request,String hql,List args){
this.hql=hql;
this.args=args;
//1 每页多少条
int max=3;
//3 共有多少页
int pages=1;
int count=this.getCount();
if(count%max==0){
pages=count/max;
}else{
pages=count/max+1;
}
//2 当前第几页
int page=1;
try{
page=Integer.parseInt(request.getParameter("page"));
}catch(Exception e){
page=1;
}
if(page>pages){
page=pages;
}
//这个if 必须写下面(这两个if 位置不能调换)
if(page<1){
page=1;
}
//从第几条开始
int begin=(page-1)*max;
List items=this.queryPage(begin, max);
request.setAttribute("items", items);
request.setAttribute("page", page);
//获得所有的参数
Map map=request.getParameterMap();
String url="";
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
String[] values=(String[])map.get(key);
if(!key.equals("page")){
for (int i = 0; i < values.length; i++) {
String value = values[i];
url+="&";
url+=key+"="+value;
}
}
}
String pageString="<a href=\"?page="+(page-1)+url+"\">上一页</a>"+
"<a href=\"?page="+(page+1)+url+"\">下一页</a>";
request.setAttribute("pageString", pageString);
}
}
- 1
- 2
前往页