Posted on 2011-02-27 18:26
viery 阅读(4003)
评论(5) 编辑 收藏 所属分类:
JavaEE
手动编写分页挺好,不过太累。于是在搜索了很多网上开源分页插件后选择pager-taglib-2.0,此分页插件因为用法简单功能强大能快速上手,下面逐步实现快速jsp页面的分页。
整体效果(因为记录比较少,所以只有两页):
第二页:
1.下载pager-taglib-2.0.war
在
http://jsptags.com/tags/navigation/pager/上可以看到demo和war包下载,在war中解压出jar包,粘贴入项目的lib文件夹中。
2.在显示的jsp上需要引入
<%@ taglib prefix="pg" uri="http://jsptags.com/tags/navigation/pager" %>
3.建立JSPPageModel模型,用于在jsp页面上返回对象集和总记录数
package com.v.oa.common;
import java.util.List;
public class JSPPageModel {
private int total;
private List list;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
4.建立SystemContext类,将系统启动时显示起始记录数和每页显示行数设置在ThreadLocal中。
package com.v.oa.common;
public class SystemContext {
private static ThreadLocal offset = new ThreadLocal();
private static ThreadLocal pagesize = new ThreadLocal();
public static void setOffset(int _offset){
offset.set(_offset);
}
public static int getOffset(){
Integer _offset = (Integer)offset.get();
if(_offset == null){
return 0;
}
return _offset;
}
public static void removeOffset(){
offset.remove();
}
public static void setPagesize(int _pagesize){
pagesize.set(_pagesize);
}
public static int getPagesize(){
Integer _pagesize = (Integer)pagesize.get();
if(_pagesize == null){
return Integer.MAX_VALUE;
}
return _pagesize;
}
public static void removePagesize(){
pagesize.remove();
}
}
5.建立过滤器,读出ThreadLocal中的显示的起始记录数和每页显示行数。这里没有在界面中去设置用户可以选择每页显示多少条记录的功能,此处固定为每页显示5条记录。
package com.v.oa.common;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class PagerFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
SystemContext.setOffset(getOffset(httpRequest));
SystemContext.setPagesize(getPagesize(httpRequest));
try{
chain.doFilter(request, response);
}finally{
SystemContext.removeOffset();
SystemContext.removePagesize();
}
}
private int getOffset(HttpServletRequest request){
int offset = 0;
try {
offset = Integer.parseInt(request.getParameter("pager.offset"));
} catch (Exception ignore) {
}
return offset;
}
private int getPagesize(HttpServletRequest request){
return 5;
}
public void init(FilterConfig arg0) throws ServletException {
}
}
6.action中:
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
OrgForm of=(OrgForm)form;
int parentId=of.getParentId();
String keyWords=request.getParameter("keyWords");
if(keyWords==null){
keyWords="";
}else{
keyWords=java.net.URLDecoder.decode(keyWords,"UTF-8");
}
//PageModel pm=orgManager.findAll(parentId, pageSize, pageNo, keyWords);
JSPPageModel pm=orgManager.findAll(parentId, keyWords);
request.setAttribute("keyWords", keyWords);
request.setAttribute("pm", pm);
我这里传了两个参数,一个是作为父类id的parentId,一个是搜索的关键字keyWords
7.ManagerImpl实现类,须继承下面的类
@Override
public JSPPageModel findAll(int parentId,String keyWords) {
keyWords="%"+keyWords+"%";
if(parentId!=0){
return this.getPage("from Organization o where o.parent.id=? and o.name like ?", new Object[]{parentId,keyWords});
}
return this.getPage("from Organization o where o.parent.id is null and o.name like ?",keyWords);
}
8.实现封装的核心class:
package com.v.oa.manager.impl;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.v.oa.common.JSPPageModel;
import com.v.oa.common.SystemContext;
/** *//**
* 此类用于封装Hibernate的分页查询
* @author Administrator
*
*/
public class PageModelManager extends HibernateDaoSupport {
public JSPPageModel getPage(String hql){
return this.getPage(hql, null,SystemContext.getOffset(),SystemContext.getPagesize());
}
public JSPPageModel getPage(String hql,int offset,int pageSize){
return this.getPage(hql, null, offset, pageSize);
}
public JSPPageModel getPage(String hql,Object o,int offset,int pageSize){
return this.getPage(hql, new Object[]{o}, offset, pageSize);
}
public JSPPageModel getPage(String hql,Object o){
return this.getPage(hql, new Object[]{o}, SystemContext.getOffset(),SystemContext.getPagesize());
}
public JSPPageModel getPage(String hql,Object[] params){
return this.getPage(hql, params, SystemContext.getOffset(),SystemContext.getPagesize());
}
public JSPPageModel getPage(String hql,Object[] params,int offset,int pageSize){
JSPPageModel pm=new JSPPageModel();
String countHql=null;
int index=hql.indexOf("from");
if(index!=-1){
countHql= "select count(*) "+hql.substring(index);
}
Query query=getSession().createQuery(countHql);
if(params!=null ||params.length>0){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
int total=((Long)(query.uniqueResult())).intValue();
pm.setTotal(total);
query=getSession().createQuery(hql);
if(params!=null ||params.length>0){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
query.setFirstResult(offset);
query.setMaxResults(pageSize);
List list=query.list();
pm.setList(list);
return pm;
}
}
整个过程结束, 最后jsp上的分页代码如下:
共 ${pm.total } 条记录
<pg:pager url="org.do" items="${pm.total }" export="currentPageNumber=pageNumber" maxPageItems="5">
<pg:param name="parentId"/>
<pg:param name="keyWords"/>
<pg:first>
<a href="${pageUrl}">首页</a>
</pg:first>
<pg:prev>
<a href="${pageUrl}">上页</a>
</pg:prev>
<pg:pages>
<c:choose>
<c:when test="${currentPageNumber eq pageNumber}">
<font color="red">${pageNumber }</font>
</c:when>
<c:otherwise>
<a href="${pageUrl}">${pageNumber }</a>
</c:otherwise>
</c:choose>
</pg:pages>
<pg:next>
<a href="${pageUrl}">下页</a>
</pg:next>
<pg:last>
<a href="${pageUrl}">尾页</a>
</pg:last>
</pg:pager>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GB18030</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>pagerFilter</filter-name>
<filter-class>com.v.oa.common.PagerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pagerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
附:
pg:pager【这个标签用来设置分页的总体参数】重要参数说明:
url:分页的链接根地址,pager标签会在这个链接的基础上附加分页参数
items:总记录数,pager标签正是根据这个值来计算分页参数的
maxPageItems:每页显示的行数,默认为10
maxIndexPages:在循环输出页码的时候,最大输出多少个页码,默认是10
pg:first【第一页的标签】重要参数说明:
export变量的意义:
pageUrl - 分页链接URL地址(最重要的export参数)
pageNumber - 页码
firstItem - 首页第一行的索引值
lastItem - 首页最后一行的索引值
pg:pre【上一页标签】重要参数说明:
export变量的意义:
pageUrl - 分页链接URL地址(最重要的export参数)
pageNumber - 页码
firstItem - 前页第一行的索引值
lastItem - 前页最后一行的索引值
pg:next【下一页标签】重要参数说明:
export变量的意义:
pageUrl - 分页链接URL地址(最重要的export参数)
pageNumber - 页码
firstItem - 下页第一行的索引值
lastItem - 下页最后一行的索引值
pg:last重要参数说明:
export变量的意义:
pageUrl - 分页链接URL地址(最重要的export参数)
pageNumber - 页码
firstItem - 尾页第一行的索引值
lastItem - 尾页最后一行的索引值
pg:pages【这个标签用来循环输出页码信息】重要参数说明:
export变量的意义:
pageUrl - 分页链接URL地址(最重要的export参数)
pageNumber - 页码
firstItem - pageNumber这个页码指定的那一页的第一行的索引值
lastItem - pageNumber这个页码指定的那一页的最后一行的索引值