一 、实现效果:
二、所需要的文件
1.下面是页面中所用到的js分页类 (PageUtil.js) 此类在网上搜集
网址 http://www.tryjs.cn #仓库收集整理
根据需要有改动
PageUtil.js
----------------------------------------------------------------------------------------------- <!-- /* showPages v1.1 ================================= Infomation ---------------------- Author : Lapuasi E-Mail : [email protected] Web : http://www.lapuasi.com Date : 2005-11-17 Example ---------------------- var pg = new showPages('pg'); pg.pageCount = 12; //定义总页数(必要) pg.argName = 'p'; //定义参数名(可选,缺省为page) pg.printHtml(); //显示页数 Supported in Internet Explorer, Mozilla Firefox */ var PageUtil = {}; function showPages(name) { //初始化属性 this.count = 0;//总记录数 PageUtil.page = this; //对象 this.name = name; this.page = 1; //当前页数 this.pageCount = 1; //总页数 this.argName = 'page'; //参数名 this.showTimes = 1; } showPages.prototype.getUrlPar = function(name){ var url = top.window.location.href; var str = ''; try{ str = url.split('?')[1].split(name+'=')[1].split('&')[0].replace('#',''); }catch(e){} return decodeURIComponent(str); } showPages.prototype.getPage = function(){ //丛url获得当前页数,如果变量重复只获取最后一个 //var args = location.search; //var reg = new RegExp('[\?&]?' + this.argName + '=([^&]*)[&$]?', 'gi'); //var chk = args.match(reg); //this.page = RegExp.$1; this.page = this.getUrlPar(this.argName); } showPages.prototype.checkPages = function(){ //进行当前页数和总页数的验证 if (isNaN(parseInt(this.page))) this.page = 1; if (isNaN(parseInt(this.pageCount))) this.pageCount = 1; if (this.page < 1) this.page = 1; if (this.pageCount < 1) this.pageCount = 1; if (this.page > this.pageCount) this.page = this.pageCount; this.page = parseInt(this.page); this.pageCount = parseInt(this.pageCount); } showPages.prototype.createHtml = function(className){ //生成html代码 //alert(className); var strHtml = '', prevPage = this.page - 1, nextPage = this.page + 1; strHtml += '<div class="'+className+'">'; if (prevPage < 1) { strHtml += '<span title="First Page" class="disabled">«</span>'; strHtml += '<span title="Prev Page" class="disabled">‹</span>'; } else { strHtml += '<span title="First Page"><a href="#:PageUtil.page.toPage(1);">«</a></span>'; strHtml += '<span title="Prev Page"><a href="#:PageUtil.page.toPage(' + prevPage + ');">‹</a></span>'; } if (this.page != 1) strHtml += '<span title="Page 1"><a href="#:PageUtil.page.toPage(1);">1</a></span>'; if (this.page >= 5) strHtml += '<span>...</span>'; var endPage; if (this.pageCount > this.page + 2) { endPage = this.page + 2; } else { endPage = this.pageCount; } for (var i = this.page - 2; i <= endPage; i++) { if (i > 0) { if (i == this.page) { strHtml += '<span title="Page ' + i + '" class="current">' + i + '</span>'; } else { if (i != 1 && i != this.pageCount) { strHtml += '<span title="Page ' + i + '"><a href="#:PageUtil.page.toPage(' + i + ');">' + i + '</a></span>'; } } } } if (this.page + 3 < this.pageCount) strHtml += '<span>...</span>'; if (this.page != this.pageCount) strHtml += '<span title="Page ' + this.pageCount + '"><a href="#:PageUtil.page.toPage(' + this.pageCount + ');">' + this.pageCount + '</a></span>'; if (nextPage > this.pageCount) { strHtml += '<span title="Next Page" class="disabled">›</span>'; strHtml += '<span title="Last Page" class="disabled">»</span>'; } else { strHtml += '<span title="Next Page"><a href="#:PageUtil.page.toPage(' + nextPage + ');">›</a></span>'; strHtml += '<span title="Last Page"><a href="#:PageUtil.page.toPage(' + this.pageCount + ');">»</a></span>'; } strHtml += '</div><br />'; return strHtml; } showPages.prototype.createUrl = function (page) { //生成页面跳转url if (isNaN(parseInt(page))) page = 1; if (page < 1) page = 1; if (page > this.pageCount) page = this.pageCount; var url = location.protocol + '//' + location.host + location.pathname; var args = location.search; var reg = new RegExp('([\?&]?)' + this.argName + '=[^&]*[&$]?', 'gi'); args = args.replace(reg,'$1'); if (args == '' || args == null) { args += '?' + this.argName + '=' + page; } else if (args.substr(args.length - 1,1) == '?' || args.substr(args.length - 1,1) == '&') { args += this.argName + '=' + page; } else { args += '&' + this.argName + '=' + page; } return url + args; } showPages.prototype.toPage = function(page){ //页面跳转 var turnTo = 1; if (typeof(page) == 'object') { turnTo = page.options[page.selectedIndex].value; } else { turnTo = page; } self.location.href = this.createUrl(turnTo); } showPages.prototype.printHtml = function(mode){ //显示html代码 var temp = 0; this.getPage(); this.checkPages(); this.showTimes += 1; document.write('<div id="pages_' + this.name + '_' + this.showTimes + '" class="pages"></div>'); document.getElementById('pages_' + this.name + '_' + this.showTimes).innerHTML = this.createHtml(mode); } showPages.prototype.formatInputPage = function(e){ //限定输入页数格式 var ie = navigator.appName=="Microsoft Internet Explorer"?true:false; if(!ie) var key = e.which; else var key = event.keyCode; if (key == 8 || key == 46 || (key >= 48 && key <= 57)) return true; return false; } //-->
注: yahoo 中把“#”明感字符给替换了,使用此JS时需要改一下。
-----------------------------------------------------------------------------------------------
2.ProdShow.jsp ---分页实现显示页
该页是用struts2 的标签实现的,也可以采用静态页面+Ajax实现,用struts标签实现起来相对简单些,根据需要咯,下面是具体代码:
ProdShow.jsp
-----------------------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html;charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'WareShow.jsp' starting page</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="css/page.css"> <style type="text/css"> table { border: 1px solid black; border-collapse: collapse; } table thead tr th { border: 1px solid black; padding: 3px; background-color: #cccccc; } table tbody tr td { border: 1px solid black; padding: 3px; } </style> <script type="text/#" src="js/mootools1.11.js"></script> <script type="text/#" src="js/demos.js"></script> <script type="text/#" src="js/PageUtil.js"></script> <script type="text/#"> window.addEvent('domready', function(){ }); </script> </head> <body> <h2>Product List</h2> <hr/> <s:form action="ProdList" theme="simple"> <table cellspacing="0" align="center"> <thead> <tr> <th><input type="hidden" id="count" /></th> <th>商品名称</th> <th>商品产地</th> <th>商品规格</th> <th>商品描述</th> </tr> </thead> <tbody> <s:iterator value="products"> <tr> <td><input type="checkBox" name="wareSel" value="<s:property value="id"/>"/></td> <td><s:property value="pname" /></td> <td><s:property value="brand" /></td> <td><s:property value="habitat" /></td> <td><s:property value="description" /></td> </tr> </s:iterator> </tbody> </table> </s:form> <div> </div> <script type="text/#"> <!-- var pg = new showPages('pg'); pg.pageCount =<s:property value="Count" />; // 定义总页数(必要) pg.printHtml('yahoo2'); //--> </script> </body> </html>
-----------------------------------------------------------------------------------------------
3. 控制层
首先控制层继承基本控制层类BaseAction.java 根据自己的实际需要是否需要此类
BaseAction.java
-----------------------------------------------------------------------------------------------
package org.leezh.demo.web.action; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { HttpServletRequest request; HttpServletResponse response; Map session; /** * */ private static final long serialVersionUID = 1L; public void setSession(Map session) { this.session = session; } public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } /*************************************************************************** * 获取页面整数参数 * * @param name * @param defalutValue * @return */ public String getStrParam(String name, String defalutValue) { String value = this.request.getParameter(name); if (value == null) { return defalutValue; } else if (value.equals("")) { return defalutValue; } else { return value; } } /*************************************************************************** * 获取页面整数参数 * * @param name * @param defalutValue * @return */ public int getIntParam(String name, int defalutValue) { String value = this.request.getParameter(name); if (value == null) { return defalutValue; } else if (value.equals("")) { return defalutValue; } else { try { return Integer.parseInt(value); } catch (Exception e) { return defalutValue; } } } /*************************************************************************** * 获取页面浮点参数 * * @param name * @param defalutValue * @return */ public float getFloatParam(String name, float defalutValue) { String value = this.request.getParameter(name); if (value == null) { return defalutValue; } else if (value.equals("")) { return defalutValue; } else { try { return Float.parseFloat(value); } catch (Exception e) { return defalutValue; } } } }
-----------------------------------------------------------------------------------------------
实际控制类ProductAction.java 继承BaseAction.java
ProductAction.java
-----------------------------------------------------------------------------------------------
package org.leezh.demo.web.action; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.leezh.demo.bean.Product; import org.leezh.demo.web.service.ProductService; public class ProductAction extends BaseAction { /** * */ private static final long serialVersionUID = 1L; private static final Log logger = LogFactory.getLog(ProductAction.class); private List<Product> products;//产品列表 private int PageCount;//总页数 private ProductService productService; public ProductAction() { logger.info("-------------Product-------------"); } @SuppressWarnings("unchecked") public String execute() { int target = this.getIntParam("page", 1); this.products = this.getProductService().findAll(target,5); this.PageCount = this.getProductService().getPageCount(); System.out.println(this.PageCount+"---------------------------"); return SUCCESS; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public ProductService getProductService() { return productService; } public void setProductService(ProductService productService) { this.productService = productService; } public int getPageCount() { return PageCount; } public void setPageCount(int pageCount) { PageCount = pageCount; } }
-----------------------------------------------------------------------------------------------
4.服务层实现
服务层接口:此接口中
》获取记录数方法 public int getPageCount();
》查询所有商品 public List findAll(int target, int pageSize);
两个方法为分页主要实现方法
具体代码:
ProductService 接口
-----------------------------------------------------------------------------------------------
package org.leezh.demo.web.service; import java.util.List; import org.leezh.demo.bean.Product; public interface ProductService { /*************************************************************************** * 查询所有商品 * * @return */ public List findAll(int target, int pageSize); /*************************************************************************** * 查询所有商品 * * @return */ public List findAll(); /*************************************************************************** * 保存商品信息 * * @param p * @return */ public Product saveProdcut(Product p); /*************************************************************************** * 根据ID删除商品 * * @param pid */ public void delProduct(int pid); /*************************************************************************** * 根据ID查询商品类 * * @param id * @return */ public Product getProductBy(int id); /*************************************************************************** * 获取记录数 * * @return */ public int getPageCount(); }
-----------------------------------------------------------------------------------------------
服务层实现 ProductServiceImp.java
-----------------------------------------------------------------------------------------------
package org.leezh.demo.web.service.imp; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.leezh.demo.bean.Product; import org.leezh.demo.comm.PageUtil; import org.leezh.demo.dao.ProductDAO; import org.leezh.demo.web.service.ProductService; public class ProductServiceImp implements ProductService { private static final Log logger = LogFactory .getLog(ProductServiceImp.class); private ProductDAO productDAO; private int pageCount; public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public void delProduct(int pid) { // TODO Auto-generated method stub } public List findAll(int target, int pageSize) { PageUtil page = this.productDAO.findAll(new PageUtil(pageSize,target)); this.setPageCount(page.getPageCount()); return page.getResult(); } public List findAll() { return this.productDAO.findAll(); } public Product getProductBy(int id) { // TODO Auto-generated method stub return null; } public Product saveProdcut(Product p) { // TODO Auto-generated method stub return null; } public ProductDAO getProductDAO() { return productDAO; } public void setProductDAO(ProductDAO productDAO) { this.productDAO = productDAO; } }
-----------------------------------------------------------------------------------------------
5.数据访问层实现
数据访问层接口ProductDAO
-----------------------------------------------------------------------------------------------
package org.leezh.demo.dao; import java.util.List; import org.leezh.demo.bean.Product; import org.leezh.demo.comm.PageUtil; public interface ProductDAO { /*************************************************************************** * 获取所有产品列表 * * @return */ public List findAll(); /*************************************************************************** * 获取所有商品(分页) * * @param page * @return */ public PageUtil findAll(PageUtil page); }
-----------------------------------------------------------------------------------------------
实现此接口ProductHibernateDAO此类中实现ProductDAO接口外还实现了HibernatePage接口,
HibernatePage接口
-----------------------------------------------------------------------------------------------
package org.leezh.demo.dao.hibernate; public interface HibernatePage { /*************************************************************************** * 获取记录总数 * * @param queryAllCount * @return */ public int getAllCount(String queryAllCount); }
-----------------------------------------------------------------------------------------------
HibernatePage接口提供一个 ---获取记录总数(即:public int getAllCount(String queryAllCount);)的定义,来实现在访问数据时对记录数总数的获取
ProductHibernateDAO.java
-----------------------------------------------------------------------------------------------
package org.leezh.demo.dao.hibernate; // default package import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.leezh.demo.bean.Product; import org.leezh.demo.comm.PageUtil; import org.leezh.demo.dao.ProductDAO; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class ProductHibernateDAO extends HibernateDaoSupport implements ProductDAO, HibernatePage { private static final Log log = LogFactory.getLog(ProductHibernateDAO.class); // property constants public static final String PNAME = "pname"; public static final String PNAME1 = "pname1"; public static final String BRAND = "brand"; public static final String HABITAT = "habitat"; public static final String DESCRIPTION = "description"; private PageUtil page; protected void initDao() { // do nothing } public PageUtil findAll(PageUtil page) { log.debug("finding all Product instances"); try { int count = getAllCount("select count(*) from Product"); page.execuePage(count); Query q = this.getSession().createQuery("from Product"); q.setFirstResult(page.getFirstResult()); q.setMaxResults(page.getPageSize()); page.setResult(q.list()); return page; } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public List findAll() { log.debug("finding all Product instances"); try { String queryString = "from Product"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public int getAllCount(String queryAllCount) { try { List list = this.getHibernateTemplate().find(queryAllCount); return Integer.parseInt(list.get(0).toString()); } catch (Exception ex) { return 0; } } }
-----------------------------------------------------------------------------------------------
三、java分页类的使用
分页类代码PageUtil.java
-----------------------------------------------------------------------------------------------
package org.leezh.demo.comm; import java.io.Serializable; import java.util.List; /******************************************************************************* * * <p> * PageUtil * </p> * * @author Leezh * */ public class PageUtil implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int count = 0; // 记录总数 private int pageSize = 20; // 每页显示记录数 private int pageCount = 0; // 总页数 private int page = 1; // 当前页数 private int firstResult = 0;// 开始记录数 private List result; public PageUtil() { } /*************************************************************************** * * @param page */ public PageUtil(int page) { this.page = page; } /*************************************************************************** * * @param count * @param pageSize */ public PageUtil(int pageSize, int page) { this.pageSize = pageSize; this.page = page; } /*************************************************************************** * * @param count * @param pageSize * @param page */ public PageUtil(int count, int pageSize, int page) { this.count = count; this.pageSize = pageSize; this.page = page; this.execuePage(); } /*************************************************************************** * * @return */ public int execuePage() { this.pageCount = ((count % pageSize == 0) ? (count / pageSize) : (count / pageSize + 1)); this.toPage(this.page); return this.pageCount; } /*************************************************************************** * * @param count * @return */ public int execuePage(int count) { this.count = count; this.pageCount = ((this.count % pageSize == 0) ? (this.count / pageSize) : (this.count / pageSize + 1)); this.toPage(this.page); return this.pageCount; } /*************************************************************************** * * @param toPage */ public void toPage(int toPage) { this.page = toPage; if (this.page > this.pageCount) { this.page = this.pageCount; } else if (this.page <= 0) { this.page = 1; } this.setResult(this.page); } /*************************************************************************** * * @param showPage */ private void setResult(int showPage) { this.firstResult = (showPage - 1) * pageSize; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getFirstResult() { return firstResult; } public void setFirstResult(int firstResult) { this.firstResult = firstResult; } public List getResult() { return result; } public void setResult(List result) { this.result = result; } }
-----------------------------------------------------------------------------------------------
此类主要在数据访问类中使用 例:
首先在服务层中向数据访问层DAO中传入PageUtil类实例
public List findAll(int target, int pageSize) { PageUtil page = this.productDAO.findAll(new PageUtil(pageSize,target)); this.setPageCount(page.getPageCount());//获取总页数 return page.getResult();//返回记录集 }
PageUtil 实例到DAO层
public PageUtil findAll(PageUtil page) { log.debug("finding all Product instances"); try { int count = getAllCount("select count(*) from Product");//查询记录总数的HQL page.execuePage(count);//根据中记录数进行分页 Query q = this.getSession().createQuery("from Product");//按SQL语句查询记录 q.setFirstResult(page.getFirstResult());//设置Hibernate开始记录数 q.setMaxResults(page.getPageSize());//设置Hibernate查询的记录数 page.setResult(q.list());//将查询列表传入PageUtil实例 return page;//返回PageUtil实例 } catch (RuntimeException re) { log.error("find all failed", re); throw re; } }
从Struts2老版本中摘出来的FreemarkerServlet,将其加入到项目中,然后在web.xml中增加下面的代码即可。
1. <!-- FreeMarker Servlet --> 2. <servlet> 3. <servlet-name>freemarker</servlet-name> 4. <servlet-class>org.apache.struts2.views.freemarker.FreemarkerServlet</servlet-class> 5. </servlet> 6. 7. <servlet-mapping> 8. <servlet-name>freemarker</servlet-name> 9. <url-pattern>*.ftl</url-pattern> 10. </servlet-mapping>