百事通信息网
web应用开发中,分页是一项很重要的技术,分页效率直接影响web应用程序的性能.当然分页除了高效,还得考虑通用性.
昨天在网上花了一天时间研究分页,今天一早就动手将自已以前的分页程序重新设计.
这里我将源代码贴出来供大家讨论,希望大家提出宝贵意见
首先封装Page类
import java.util.List;
public class Page {
private boolean hasPrevPage;//是否存在上一页
private boolean hasNextPage;//是否存在下一页
private int pageSize;//每页容量
private int totalPage;//总页数
private int totalRow;//总记录数
private int curPage;//当前页
private int beginIndex;//当前页开始索引号
private String url;//该页URL地址
private String param;//参数以&分隔
private String pageToolBar;//分页工具条
private List result;//当前页结果集(记录集)
/**
* 功能:初始化数据(查询前)
* @param pageSize
* @param url
* @param param
*/
public Page(int pageSize,String url,String param) {
this.pageSize=pageSize;
this.url=(null==url)?"":url;
this.param=(null==param)?"":param;
}
/**
* 功能:初始化数据(查询后)
* @param hasPrevPage
* @param hasNextPage
* @param pageSize
* @param totalPage
* @param totalRow
* @param curPage
* @param beginIndex
* @param pageToolBar
*/
public Page(boolean hasPrevPage, boolean hasNextPage,int pageSize, int totalPage, int totalRow,int curPage, int beginIndex,String pageToolBar){
this.hasPrevPage=hasPrevPage;
this.hasNextPage=hasNextPage;
this.pageSize=pageSize;
this.totalPage=totalPage;
this.totalRow=totalRow;
this.curPage=curPage;
this.beginIndex=beginIndex;
this.pageToolBar=pageToolBar;
}
public List getResult() {
return result;
}
public void setResult(List result) {
this.result = result;
}
public int getBeginIndex() {
return beginIndex;
}
public void setBeginIndex(int beginIndex) {
this.beginIndex = beginIndex;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public boolean isHasPrevPage() {
return hasPrevPage;
}
public void setHasPrevPage(boolean hasPrevPage) {
this.hasPrevPage = hasPrevPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalRow() {
return totalRow;
}
public void setTotalRow(int totalRow) {
this.totalRow = totalRow;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getPageToolBar() {
return pageToolBar;
}
public void setPageToolBar(String pageToolBar) {
this.pageToolBar = pageToolBar;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
建PageUtil类,用来构告Page类的数据
public class PageUtil {
private final static int DEF_PAGE_SIZE = 10;//默认当前页的容量
/**
* 功能:传入查询前初始化的page实例,创建一个新的Page实例
* @param page
* @param totalRow
* @return
*/
public static Page createPage(Page page, int totalRow) {
return createPage(page.getUrl(),page.getParam(),page.getPageSize(), page.getCurPage(), totalRow);
}
public static Page createPage(String url,String param,int pageSize, int curPage, int totalRow) {
pageSize = getpageSize(pageSize);
curPage = getcurPage(curPage);
int beginIndex = getBeginIndex(pageSize, curPage);
int totalPage = getTotalPage(pageSize, totalRow);
boolean hasNextPage = hasNextPage(curPage, totalPage);
boolean hasPrePage = hasPrePage(curPage);
String pageToolBar=getPageToolBar(url,param,hasPrePage, hasNextPage, pageSize, totalPage, totalRow,curPage);
return new Page(hasPrePage, hasNextPage, pageSize, totalPage, totalRow,
curPage, beginIndex,pageToolBar);
}
private static String getPageToolBar(String url,String param,boolean hasPrePage, boolean hasNextPage, int pageSize, int totalPage, int totalRow,int curPage){
StringBuffer strBuf=new StringBuffer();
boolean isHaveParam=false;
if(null!=param && !"".equals(param)){
isHaveParam = true;
}
strBuf.append("当前第"+curPage+"页/共"+totalPage+"页 总记录"+totalRow+"条");
if(hasPrePage){
strBuf.append(" <a href=\""+url+"?page=1"+((isHaveParam)?"&"+param:"")+"\">首页</a>");
strBuf.append(" <a href=\""+url+"?page="+(curPage - 1)+((isHaveParam)?"&"+param:"")+"\">上一页</a>");
}else{
strBuf.append(" 首页 上一页");
}
if(hasNextPage){
strBuf.append(" <a href=\""+url+"?page="+(curPage + 1)+((isHaveParam)?"&"+param:"")+"\">下一页</a>");
strBuf.append(" <a href=\""+url+"?page="+totalPage+((isHaveParam)?"&"+param:"")+"\">尾页</a>");
}else{
strBuf.append(" 下一页 尾页");
}
return strBuf.toString();
}
private static int getpageSize(int pageSize) {
return pageSize == 0 ? DEF_PAGE_SIZE : pageSize;
}
private static int getcurPage(int curPage) {
return curPage == 0 ? 1 : curPage;
}
private static int getBeginIndex(int pageSize, int curPage) {
return (curPage - 1) * pageSize;
}
private static int getTotalPage(int pageSize, int totalRow) {
int totalPage = 0;
if (totalRow % pageSize == 0)
totalPage = totalRow / pageSize;
else
totalPage = totalRow / pageSize + 1;
return totalPage;
}
private static boolean hasPrePage(int curPage) {
return curPage == 1 ? false : true;
}
private static boolean hasNextPage(int curPage, int totalPage) {
return curPage == totalPage || totalPage == 0 ? false : true;
}
}
以上二个类与业务层无关,接下来结合业务层应用,给出以下代码
用户操作业务的接口:
import com.note.comm.Page;
import com.note.dao.UsersDAO;
import com.note.model.Users;
public interface IUserService {
public UsersDAO getUsersDao();
public void setUsersDao(UsersDAO usersDao);
......
/**
* 功能:得到当前页的分页信息与当前页的记录集(存入在page的result属性中)
* @param page
* @return
*/
public Page listUsers(Page page);
......
}
用户操作业务的具体实现:
UserService
import java.util.List;
import com.note.bussies.service.IUserService;
import com.note.comm.Page;
import com.note.comm.PageUtil;
import com.note.dao.UsersDAO;
import com.note.model.Users;
public class UserService implements IUserService {
private UsersDAO usersDao;
public UsersDAO getUsersDao() {
return usersDao;
}
public void setUsersDao(UsersDAO usersDao) {
this.usersDao = usersDao;
}
......
public Page listUsers(Page page){
int totalRecords = this.usersDao.getUserCount();
page = PageUtil.createPage(page, totalRecords);
if(totalRecords == 0)return page;
List users = this.usersDao.getUsersByPage(page);
page.setResult(users);
return page;
}
}
UserService调用UserDao的方法实现分页,UserDao代码如下:
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.note.comm.Page;
import com.note.model.Users;
/**
* Data access object (DAO) for domain model class Users.
* @see com.note.dao.Users
* @author MyEclipse - Hibernate Tools
*/
public class UsersDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UsersDAO.class);
//property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String LEVEL = "level";
protected void initDao() {
//do nothing
}
......
public int getUserCount(){
int count = 0;
String querySentence = "SELECT count(*) FROM Users";
Session s=getSession();
Query query = s.createQuery(querySentence);
count = ((Integer)query.iterate().next()).intValue();
releaseSession(s);//注意,些处必须关闭Session
return count;
}
public List getUsersByPage(final Page page){
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session s){
Query query=s.createQuery("From Users AS users ORDER BY users.userid");
query.setFirstResult(page.getBeginIndex());
query.setMaxResults(page.getPageSize());
return query.list();
}
});
}
}
至此,一个完整的分页程序完成。下页给出Struts调用示例
action类:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import com.note.bussies.service.IUserService;
import com.note.comm.Page;
import com.note.comm.ParamUtil;
import com.note.model.Users;
import com.note.sys.Constant;
/**
* MyEclipse Struts
* Creation date: 10-09-2006
*
* XDoclet definition:
* @struts.action path="/user" name="userForm" input="/form/user.jsp" scope="request"
* @struts.action-forward name="success" path="/success.htm" redirect="false"
* @struts.action-forward name="fail" path="/fail.htm" redirect="false"
*/
public class UserAction extends DispatchAction {
private IUserService ius;
public IUserService getIus() {
return ius;
}
public void setIus(IUserService ius) {
this.ius = ius;
}
public ActionForward display(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//获得url
String contextPath = request.getContextPath();
String PathName="listUser" + Constant.FILEPREFIX;
String url=contextPath+"/"+PathName;
//获得参数
int curPage = ParamUtil.getInt(request, "page", 1);
String method=ParamUtil.getString(request, "method", "display");
String param="method="+method;
Page page=new Page(3,url,param);
page.setCurPage(curPage);
page=this.ius.listUsers(page);
request.setAttribute("users",page);//保存到request中
return mapping.findForward("success");
}
}
view页面:
<logic:present name="users">
<table>
<logic:iterate id="user" name="users" indexId="number" property="result">
<tr>
<td>
<bean:write name="number" />
<bean:write name="user" property="userid" />
<bean:write name="user" property="username" />
</td>
</tr>
</logic:iterate>
</table>
<bean:write name="users" property="pageToolBar" filter="false" />
</logic:present>
以上代码参考了downpour跟水如清二位仁兄的设计思想,特些声明.