- 相当不错的JS分页代码
- <!--
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
- /**
- * 用js分页显示ul/ol的列表
- *
- * 这里的演示设置了自动滚动
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @package GCCMS
- * @author Yi Bo <etng2004@gmail.com>
- * @copyright 2000-2005 GCSOFT.COM & ETNG.NET
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version SVN: $Id: page.html 21 2006-01-22 09:35:58Z etng $
- * @link $HeadURL: svn://dev.gccms.net/trunk/page.html $
- * @see
- * @since
- */
- --><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
- <title>无标题文档</title>
- <style type="text/css">
- <!--
- /*这里填写自己需要的css定义*/
- body { width: 760px; padding: 0 0 0 0; margin: 0 auto 0 auto; font-size: 12px; font-family: "Arial", "Helvetica", "sans-serif"; }
- td { font-size: 12px; }
- ul,li,form,div,span { padding: 0 0 0 0; margin: 0 0 0 0; }
- .ctrlPages {COLOR: #f60;}
- .curPage {COLOR: #f00;}
- -->
- </style>
- <script language="JavaScript">
- <!--
- var ETNGpager = function( srcName, dstName, cntPP, cntPS )
- {
- this.srcName = srcName;
- this.dstName = dstName;
- this.curP = 1;//默认当前页为第一页
- this.cntPP = cntPP || 2;//默认每页两条纪录
- this.cntPS = cntPS || 3;//默认每页显示5个分页上下文
- this.items = [];
- this.showPNP = true;/*显示上下页链接*/
- this.showType = true;/*滑动分页*/
- this.result = {pagedata:[],pagebar:'',limit:[0,0],report:''};
- this.parse();/*总纪录数*/
- }
- ETNGpager.prototype.page = function (){
- this.cntP = Math.ceil(this.cntR/this.cntPP);/*总页数*/
- this.cntS = Math.ceil(this.cntP/this.cntPS);/*总段数*/
- this.curS = Math.ceil(this.curP/this.cntPS);/*当前段*/
- this.preP = this.curP -1;/*上一页*/
- this.nextP = this.curP +1;/*下一页*/
- this.preS = this.curS -1;/*上一段*/
- this.nextS = this.curS +1;/*下一段*/
- this.startR = (this.curP -1)*this.cntPP + 1;/*起始纪录*/
- this.endR = (this.curP*this.cntPP >this.cntR)?this.cntR:this.curP*this.cntPP;/*结束纪录*/
- this.result['pagedata']=[];
- if(this.showType){
- this.perSide = Math.floor(this.cntPS/2);
- this.startP = (this.curP > this.perSide)?(this.curP - this.perSide):1;
- this.endP = (this.startP + this.cntPS)>this.cntP?this.cntP:(this.startP + this.cntPS);
- }else{
- this.startP = (this.curS-1)*this.cntPS+1;
- this.endP = (this.curS*this.cntPS>this.cntP)?this.cntP:(this.curS*this.cntPS);
- }
- for(var i = this.startP;i<=this.endP;i++){
- this.result['pagedata'].push((i==this.curP)?'<span class="curPage">'+i+'</span>':'<span οnclick="page('+i+')">'+i+'</span>');
- }
- if(this.showPNP){
- if(this.curP>1)this.result['pagedata'].unshift('<span οnclick="page('+(this.curP-1)+')">上一页</span>');
- if(this.curP<this.cntP)this.result['pagedata'].push('<span οnclick="page('+(this.curP+1)+')">下一页</span>');
- }
- this.result['pagebar'] = this.result['pagedata'].join(' ');
- this.result['limit'] = [this.startR,this.endR];
- this.result['report'] = '共'+this.cntR+'条,当前页'+this.startR+'-'+this.endR+','+this.curP+'/'+this.cntP+'页';
- }
- ETNGpager.prototype.parse = function (){
- var obj = document.getElementById(this.srcName);
- for(var i = 0;i<obj.childNodes.length;i++){
- if(obj.childNodes[i].nodeType!=3)this.items[this.items.length]=obj.childNodes[i].innerHTML;
- }
- this.cntR = this.items.length;
- return this.items.length;
- }
- ETNGpager.prototype.create=function(){
- this.page();
- document.getElementById(this.dstName).innerHTML='<li>'+this.items.slice(this.startR-1,this.endR).join('</li><li>')+'</li>';
- document.getElementById(this.dstName).innerHTML+='<span class="ctrlPages">'+this.result['pagebar']+this.result['report']+'</span>';
- }
- //-->
- </script>
- </head>
- <body>
- <ul id="listcontent" style="display:none;">
- <li><a href=http://tech.sina.com.cn/i/2005-12-08/1204786367.shtml target='_blank'>支付宝与六大代理签订协议 </a></li>
- <li><a href=http://forum.taobao.com/showThread.htm?thread=3123988&forum=14 target='_blank'>刷卡积分可网上购物 </a></li>
- <li><a href=/alipay/news/sample/23492.htm target='_blank'>支付宝为网店保驾护航 </a></li>
- <li><a href=http://it.people.com.cn/GB/8219/50656/52310/3822563.html target='_blank'>支付宝红包送来红地毯 </a></li>
- <li><a href=/alipay/news/sample/22701.htm target='_blank'>紧急天气预报"红色风暴"空降支付宝 </a></li>
- <li><a href=/alipay/news/sample/22699.htm target='_blank'>小红包背后大名堂 </a></li>
- <li><a href=http://www.q88.net/SHOP_2005A/zfb.aspx target='_blank'>Q88.net全面无缝接合支付宝 </a></li>
- <li><a href=/alipay/news/sample/21529.htm target='_blank'>电子支付规范走出第一步 使用专业版受鼓励 </a></li>
- <li><a href=/alipay/news/sample/19786.htm target='_blank'>从支付宝看电子商务的发展 </a></li>
- <li><a href=/alipay/news/sample/19784.htm target='_blank'>谁能与支付宝PK? </a></li>
- <li><a href=/alipay/news/sample/19618.htm target='_blank'>国内第一家引入支付宝的网络图库正式开通 </a></li>
- <li><a href=/alipay/news/sample/19475.htm target='_blank'>新浪网:中关村在线加入支付宝联盟 </a></li>
- <li><a href=/alipay/news/sample/19471.htm target='_blank'>千家网店加入支付宝联盟 </a></li>
- <li><a href=/alipay/news/sample/18549.htm target='_blank'>我与支付宝的分分秒秒 </a></li>
- <li><a href=/alipay/news/sample/18207.htm target='_blank'>支付宝—放心“网宝”的理由 </a></li>
- <li><a href=/alipay/news/sample/17944.htm target='_blank'>欧飞数卡携手支付宝,再创新高 </a></li>
- <li><a href=/alipay/news/sample/17803.htm target='_blank'>莎莎香水网:支付宝助我完成销售计划 </a></li>
- <li><a href=/alipay/news/sample/17801.htm target='_blank'>使用支付宝:一个月交易额翻5倍 </a></li>
- <li><a href=/alipay/news/sample/17799.htm target='_blank'>支付宝:一个普通站长的自述 </a></li>
- <li><a href=/alipay/news/sample/17797.htm target='_blank'>新开网店如何日交易额达8000元? </a></li>
- <li><a href=/alipay/news/sample/17563.htm target='_blank'>名大数码:网店月交易额如何突破30万 </a></li>
- <li><a href=http://it.sohu.com/20050916/n240400443.shtml target='_blank'>中国卡网结盟支付宝创交易量周增长新高 </a></li>
- <li><a href=http://it.people.com.cn/GB/42891/42894/3676101.html target='_blank'>支付宝联盟与合作伙伴合作在人民网推广 </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---103546-.htm target='_blank'>网络银行使用全攻略---足不出户查看汇款明细 </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---1561087-.htm target='_blank'>"支付宝购物体验"征文-----贿赂 </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---2102458-.htm target='_blank'>卖家谈:谁是支付宝最终的获利者? </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---1617047-.htm target='_blank'>淘宝两钻卖家感悟支付宝 </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---1686484-.htm target='_blank'>支付宝“即时到帐交易”的使用经验及建议 </a></li>
- <li><a href=http://forum.taobao.com/show_thread-50---1794216-.htm target='_blank'>我的第一笔网上交易 </a></li>
- </ul>
- <ul id="listcontent2">列表信息加载中,请您稍等……</ul>
- <script language="JavaScript">
- <!--
- var pager = new ETNGpager('listcontent','listcontent2',10,5);
- var curP = 1;
- showtime = setInterval("page()", 5000);
- function page(i){
- curP =(curP>pager.cntP)?1:curP;
- if(i){
- curP = n =i;
- }else{
- n = curP++;
- }
- pager.curP = (n>pager.cntP)?pager.cntP:n;
- pager.create();
- }
- //-->
- </script>
- </body>
- </html>
- JAVA 反射技术 万用分页标签 核心代码
- Java中,反射是一种强大的工具。它使您能够创建灵活的代码,这些代码可以在运行时装配,无需在组件之间进行源代表链接。反射允许我们在编写与执行时, 使我们的程序代码能够接入装载到JVM中的类的内部信息,而不是源代码中选定的类协作的代码。这使反射成为构建灵活的应用的主要工具。但需注意的是:如果 使用不当,反射的成本很高。
- 下面要介绍的例子是我从事struts开发时开发 万用分页标签 所用到的技术,该标签能根据传入的bean list自动生成分页表格
- 很多框架级应用中都必须用反射技术才能达到灵活泛用的目的,典型的struts,spring,hibernate等
- 下面我们就切入正题,看看反射技术是怎么应用的
- 首先我们建立一个工程,名为JavaReflect,再建立TestBean,TestMain,TabTest存入com.sdna.reflect包中
- 结构如下
- 如图:1
- <!--[if !vml]--><!--[endif]-->
- ==========TestBean 为任意一个符合Bean命名规范的类
- package com.sdna.reflect;
- public class TestBean {
- private int userID;
- private String userName;
- private String userSex;
- private int userAge;
- private String userAddr;
- public TestBean() {
- try {
- jbInit();
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- }
- private void jbInit() throws Exception {
- }
- public void setUserID(int userID) {
- this.userID = userID;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public void setUserSex(String userSex) {
- this.userSex = userSex;
- }
- public void setUserAge(int userAge) {
- this.userAge = userAge;
- }
- public void setUserAddr(String userAddr) {
- this.userAddr = userAddr;
- }
- public int getUserID() {
- return userID;
- }
- public String getUserName() {
- return userName;
- }
- public String getUserSex() {
- return userSex;
- }
- public int getUserAge() {
- return userAge;
- }
- public String getUserAddr() {
- return userAddr;
- }
- }
- ====================
- ==========TestMain 为测试打印某实例所有方法,参数,返回值
- package com.sdna.reflect;
- import java.lang.reflect.*;
- public class TestMain {
- public TestMain() {
- }
- public static void main(String[] args) {
- TestBean obj = new TestBean();
- Class c = obj.getClass();
- Method[] theMethods = c.getMethods();
- for (int i = 0; i < theMethods.length; i++) {
- String methodString = theMethods[i].getName();
- System.out.println("Name: " + methodString);
- String returnString =
- theMethods[i].getReturnType().getName();
- System.out.println(" Return Type: " + returnString);
- Class[] parameterTypes = theMethods[i].getParameterTypes();
- System.out.print(" Parameter Types:");
- for (int k = 0; k < parameterTypes.length; k++) {
- String parameterString = parameterTypes[k].getName();
- System.out.print(" " + parameterString);
- }
- System.out.println("/n");
- }
- try {
- theMethods[2].invoke(obj, "sky");
- System.out.println(obj.getUserName());
- } catch (InvocationTargetException ex) {
- ex.printStackTrace();
- } catch (IllegalArgumentException ex) {
- ex.printStackTrace();
- } catch (IllegalAccessException ex) {
- ex.printStackTrace();
- }
- }
- }
- ====================
- ==========TabTest 为读任意一个符合Bean命名规范的实例
- package com.sdna.reflect;
- import java.lang.reflect.*;
- public class TabTest {
- public TabTest() {
- }
- public static void main(String[] args) {
- TestBean obj = new TestBean();
- obj.setUserID(10001);
- obj.setUserName("sky");
- obj.setUserSex("boy");
- obj.setUserAge(23);
- obj.setUserAddr("wuhan");
- Class objClass = obj.getClass();
- Field fields[] = objClass.getDeclaredFields();
- // Method[] methods = objClass.getMethods();
- Method tempMethod = null;
- String strMethod = null;
- for (int i = 0; i < fields.length; i++) {
- try {
- String fieldName = fields[i].getName();
- Class typeClass = fields[i].getType();
- String fieldType = typeClass.getName();
- strMethod = fieldName;
- strMethod = "get" +
- strMethod.replaceFirst(strMethod.substring(0, 1),
- strMethod.substring(0, 1).toUpperCase());
- tempMethod = objClass.getMethod(strMethod);
- System.out.println("Name: " + fieldName + ", Type: "
- + fieldType + ", Values: " + tempMethod.invoke(obj));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
- }
- ====================
- TestMain运行结果
- 如图:2
- <!--[if !vml]--><!--[endif]-->
- TabTest运行结果
- 如图:2
- <!--[if !vml]--><!--[endif]-->
- jsp 自定义分页标签
- 花了一上午简单研究了下自定义标签。就弄了个自定义的分页标签。代码没有怎么仔细优化。先贴上来,:)
- 1,标签的实现类NumenTag.java
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.JspWriter;
- import javax.servlet.jsp.tagext.TagSupport;
- /** *//**
- * 自定义的分页标签
- *
- * @author 马万林
- *
- */
- public class NumenTag extends TagSupport {
- private String url = null;
- private Result result;
- private String page = null;
- private String[] p;
- private Map kv = new HashMap();
- private List key = null;
- /** *//**
- * 分离参数
- * @param params
- */
- public void setParams(String params) {
- key = new ArrayList();
- p = params.split(";");
- for (int i = 0; p.length>1&&i < p.length; i++) {
- kv.put(p[i].split(":")[0], p[i].split(":")[1]);
- key.add(p[i].split(":")[0]);
- }
- }
- /** *//**
- * 分页的结果
- * @param result
- */
- public void setResult(String result) {
- this.result = (Result) pageContext.getRequest().getAttribute("result");
- this.page = (String) pageContext.getRequest().getAttribute("page");
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public int doStartTag() throws JspException {
- StringBuffer sb = null;
- if (result != null && result.getContent() != null
- && result.getContent().size() > 0) {
- sb = new StringBuffer("分页: ");
- if (result.getPage().getHasPrePage()){
- sb.append("<a href='").append(url);
- if (url.indexOf("?") == -1)
- sb.append("?page=1");
- else
- sb.append("&page=1");
- linkParams(sb);
- sb.append("'>").append("首页").append("</a>").append(" | ");
- sb.append("<a href='").append(url);
- if (url.indexOf("?") == -1)
- sb.append("?page=").append(
- result.getPage().getPreviousPage());
- else
- sb.append("&page=").append(
- result.getPage().getPreviousPage());
- linkParams(sb);
- sb.append("'>").append("上页").append("</a>").append(" | ");
- }
- if (result.getPage().getHasNextPage()) {
- sb.append("<a href='").append(url);
- if (url.indexOf("?") == -1)
- sb.append("?page=").append(result.getPage().getNextPage());
- else
- sb.append("&page=").append(result.getPage().getNextPage());
- linkParams(sb);
- sb.append("'>").append("下页").append("</a>").append(" | ");
- sb.append("<a href='").append(url);
- if (url.indexOf("?") == -1)
- sb.append("?page=").append(result.getPage().getTotalPage());
- else
- sb.append("&page=").append(result.getPage().getTotalPage());
- linkParams(sb);
- sb.append("'>").append("尾页").append("</a>");
- }
- sb
- .append(" 跳转到:<select name='goToPage' οnchange='javascript:goPage(this.value)'>");
- int s = result.getPage().getTotalCount();
- for (int i = 1; i <= s; i++) {
- sb.append("<option value=").append(i);
- if (Integer.parseInt(page) == i)
- sb.append(" selected");
- sb.append(">第").append(i).append("页</option>");
- }
- sb.append("</select>");
- sb.append("<script language=javascript>");
- sb.append("function goPage(page){").append("window.location='")
- .append(url);
- if (url.indexOf("?") == -1)
- sb.append("?page='+").append("page");
- else
- sb.append("&page='+").append("page");
- sb.append("+'");
- linkParams(sb);
- sb.append("';");
- sb.append("}");
- sb.append("</script>");
- }
- try {
- if (sb != null) {
- JspWriter out = pageContext.getOut();
- out.print(sb);
- }
- } catch (Exception e) {
- throw new JspException(e);
- }
- return EVAL_PAGE;
- }
- /** *//**
- * 链接参数处理
- * @param sb
- */
- private void linkParams(StringBuffer sb) {
- for (int i = 0; i < key.size(); i++) {
- sb.append("&").append(key.get(i)).append("=").append(
- kv.get(key.get(i)));
- }
- }
- }
- 2,标签定义文件numentag.tld
- <?xml version="1.0" encoding="utf-8" ?>
- <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
- <taglib>
- <tlib-version>1.0</tlib-version>
- <jsp-version>1.2</jsp-version>
- <short-name>numen</short-name>
- <!--OutputTag-->
- <tag>
- <name>out</name>
- <tag-class>cn.cityyouth.util.NumenTag</tag-class>
- <body-content>empty</body-content>
- <attribute>
- <name>url</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>result</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>params</name>
- <required>false</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- </tag>
- </taglib>
- 3.js
- <%@ page contentType="text/html; charset=utf-8"%>
- <%@ include file="/common/taglibs.jsp"%>
- <%@ taglib uri="/WEB-INF/numentag.tld" prefix="n"%>
- <html>
- <head>
- </head>
- <body>
- <table>
- <tr><td>
- <n:out url="test.do" result="result" params="${type}"/>
- </td></tr>
- </table>
- </body>
- </html>
- 利用向量实现分页的一种方式
- /** 当前页 */
- private int nowPage = 1;
-
- /** 最大页 */
- private int maxPage = 0;
-
- /** 显示数目 */
- private String showRows = new String();
-
- /**全部Vector */
- private Vector allList = new Vector();
-
- /** 每页Vector */
- private Vector resultList = new Vector();
-
- //改变页数,更新变量
- public ChangePage(Vector pList, int pNowPage, String pShowRows) {
-
- this.allList = pList;
- //当前页
- try {
- this.nowPage = pNowPage;
- if (this.nowPage == 0) {
- this.nowPage = 1;
- }
- } catch (Exception e) {
- this.nowPage = 1;
- }
-
- //显示数目
- try {
- if (!pShowRows.equals(Constants.SHOWALL)) {
- if (Integer.parseInt(pShowRows)==0) {
- this.showRows = Constants.SHOWALL;
- } else {
- this.showRows = pShowRows;
- }
- } else {
- this.showRows = pShowRows;
- }
- } catch (Exception e) {
- this.showRows = Constants.SHOWALL;
- }
-
- //最大页,每页
- if (this.showRows.equals(Constants.SHOWALL)) {
- //当前页
- this.resultList = pList;
- //最大页
- this.maxPage = 1;
- } else {
- //显示数目
- int counts = Integer.parseInt(this.showRows);
- int tmpCount = 0;
- Vector vAllPage = new Vector();
- Vector vOnePage = new Vector();
- for (int i=0; i<THIS.ALLLIST.SIZE(); (tmpCount if tmpCount++; { i++)>counts) {
- vAllPage.add(vOnePage);
- vOnePage = new Vector();
- tmpCount = 1;
- }
- vOnePage.add(allList.get(i));
- }
- if (tmpCount<=counts) {
- vAllPage.add(vOnePage);
- }
-
- this.maxPage = vAllPage.size();
-
- if (this.nowPage>this.maxPage) {
- this.nowPage = this.maxPage;
- }
- this.resultList = (Vector) vAllPage.get(this.nowPage-1);
-
- }
- }
- hibernate分页
- 分页在任何系统中都是非常头疼的事情,有的数据库在语法上支持分页,而有的数据库则需要使用可滚动游标来实现,并且在不支持可滚动游标的系统上只能使用单向游标逐步接近要取得的数据。
- Hibernate提供了一个支持跨系统的分页机制,这样无论底层是什么样的数据库都能用统一的接口进行分页操作。比如下面的代码就是从第500条开始取出100条记录:
- Query q = session.createQuery("from FooBar as f");
- q.setFirstResult(500);
- q.setMaxResults(100);
- List l = q.list();
- 那么Hibernate底层如何实现分页的呢?Hibernate根据Query拼装SQL语句的地方是在org.hibernate.loader.Loader类的prepareQueryStatement方法中,对分页支持的代码在这一段中可以发现:
- if (useLimit)
- {
- sql = dialect.getLimitString(
- sql.trim(), //use of trim() here is ugly?
- useOffset ? getFirstRow(selection) : 0,
- getMaxOrLimit(selection, dialect)
- );
- }
- 此处调用Dialect的getLimitString方法来得到不同平台的分页语句。
- 在MySQLDialect中是如下实现getLimitString方法的:
- public String getLimitString(String sql, boolean hasOffset)
- {
- return new StringBuffer( sql.length()+20 )
- .append(sql)
- .append( hasOffset ? " limit ?, ?" : " limit ?")
- .toString();
- }
- 这是MySQL的专用分页语句,再来看Oracle9Dialect:
- public String getLimitString(String sql, boolean hasOffset) {
- sql = sql.trim();
- boolean isForUpdate = false;
- if ( sql.toLowerCase().endsWith(" for update") ) {
- sql = sql.substring( 0, sql.length()-11 );
- isForUpdate = true;
- }
- StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
- if (hasOffset) {
- pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
- }
- else {
- pagingSelect.append("select * from ( ");
- }
- pagingSelect.append(sql);
- if (hasOffset) {
- pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
- }
- else {
- pagingSelect.append(" ) where rownum <= ?");
- }
- if ( isForUpdate ) {
- pagingSelect.append( " for update" );
- }
- return pagingSelect.toString();
- }
- Oracle采用嵌套3层的查询语句结合rownum来实现分页,这在Oracle上是最好的方式,因为如果只是一层或者两层的查询语句的rownum不能支持order by。
- 此 外Interbase,PostgreSQL,HSQL等也在语法级别上支持分页,具体实现可以查看相应的Dialect实现。如果数据库不支持分页的 SQL语句,那么如果数据库支持可滚动游标,那么Hibernate就会采使用ResultSet的absolute方法直接移到查询起点;否则使用循环 语句,通过rs.next一步步移动到要查询的数据处:
- final int firstRow = getFirstRow( selection );
- if ( firstRow != 0 )
- {
- if ( getFactory().getSettings().isScrollableResultSetsEnabled() )
- {
- // we can go straight to the first required row
- rs.absolute( firstRow );
- }
- else
- {
- // we need to step through the rows one row at a time (slow)
- for ( int m = 0; m < firstRow; m++ ) rs.next();
- }
- }
- 可见使用Hibernate,在进行查询分页的操作上,是具有非常大的灵活性,Hibernate会首先尝试用特定数据库的分页sql,如果没 用,再尝试Scrollable,如果不支持Scrollable再采用rset.next()移动的办法。这样既兼顾了查询分页的性能,同时又保证了代 码在不同的数据库之间的可移植性。
- Jsp 分页代码1
- <%@ page contentType= "text/html; charset=GBK " %>
- <%@page import= "java.util.ArrayList "%>
- <%@page import= "java.util.Iterator "%>
- <%@page import= "bean.xxx.bean名 "%>
- <jsp:useBean id= "db " scope= "page " class= "database.连接数据库的类 "/>
- <jsp:useBean id= "bean自己起的名 " scope= "page " class= "bean.xxx.bean名 "/>
- ......
- <!--分页================================================================-->
- <%
- String p = request.getParameter( "page ");
- int tempPage = 1;
- if (p != null)
- tempPage = Integer.parseInt(p);
- //从会话里得到的 ArrayList
- ArrayList list = (ArrayList) session.getAttribute( "放入会话的 ArrayList 名 ");
- //如果会话里没有值 也就是第一次到本页面进行的处理 可保证不出现空指针异常
- if(list == null){
- String sql = "select * from 表名 ";
- list = db.自己写的得到ArrayList的方法(sql);
- }
- int recordsCount = list.size(); //总记录数
- // System.out.println(recordsCount);
- int pageSize = 10; //每页记录数 可以改成任意数值
- int pagesCount = (recordsCount + pageSize - 1) / pageSize; //总页数
- // System.out.println(pagesCount);
- if (tempPage < 0)
- tempPage = 1;
- if (tempPage > pagesCount)
- tempPage = pagesCount;
- int curPage = tempPage; //当前页结束页码
- // System.out.println(curPage);
- int start = (curPage - 1)*pageSize; //当前页起始页码
- // System.out.println(start);
- int end = curPage*pageSize + 1; //当前页结束页码
- // System.out.println(end);
- int i = 0;
- Iterator it = list.iterator(); //叠代
- while (it.hasNext()) { //it.hasNext()判断有无下一条记录
- bean自己起的名 = (bean名) it.next(); //it.next()指针指向下一条
- i++;
- if (i > start && i < end) {
- %>
- <!--=====================================================================-->
- ........
- <tr>
- <td> <%=bean自己起的名.getXXXXX()%> </td>
- </tr>
- .......
- <!--分页==========================================-->
- <%
- }
- }
- %>
- <tr bgcolor= "#ffffff ">
- <td height= "27 " colspan= "3 "> <div align= "center ">
- <%if (curPage != 1) {%>
- <a href= "本页面名.jsp?page=1 "> 第一页 </a> <a href= "本页面名.jsp?page= <%=curPage-1%> "> 上一页 </a>
- <%
- }
- if (curPage != pagesCount) {
- %>
- <a href= "本页面名.jsp?page= <%=curPage+1%> "> 下一页 </a> <a href= "本页面名.jsp?page= <%=pagesCount%> "> 最后一页 </a>
- <%}%>
- </div> </td>
- </tr>
- <!--=========================================================-->
- Jsp 分页代码2
- jsp列表下方加上
- <%
- int startRow = 0,totalRow=0;
- try {startRow=Integer.parseInt(request.getParameter( "statrow "));}catch (Exception ex) {}
- try {totalRow=Integer.parseInt((String)request.getAttribute( "totalRow "));}catch (Exception ex) {}
- PageDivider pageDiv = new PageDivider(selfUrl, "a=a ",totalRow,startRow,15);
- %>
- <table border= "0 ">
- <%=pageDiv.getFontTypeOut()%>
- </table>
- pageDiv类
- package com.sc.util;
- /**
- * <p> Title:用于分页时简化在jsp页面出现太多java代码 </p>
- * <p> Description: </p>
- * <p> Copyright: Copyright (c) 2003 </p>
- * <p> Company:drgsqd </p>
- * @author unascribed
- * @version 1.0
- */
- public class PageDivider implements java.io.Serializable {
- private String _selfPath=null;
- private String _paraStr=null;
- private int _totalRow=0;
- private int _startRow=0;
- private int _showRow=0;
- /自身参数
- private int _priRow = 0;
- private int _nextRow = 0;
- private int _endRow = 0;
- private int _totalPage = 0;
- private int _nowPage = 0;
- public PageDivider(String selfPath,String paraStr,int totalRow,int startRow,int showRow) {
- this._selfPath = selfPath;
- this._paraStr = paraStr;
- this._totalRow = totalRow;
- this._startRow = startRow;
- this._showRow = showRow;
- initValues();
- }
- private void initValues(){
- if(this._paraStr==null)this._paraStr= " ";
- if(this._selfPath==null)this._selfPath= " ";
- if(this._showRow> this._totalRow)this._startRow=0;
- if(this._startRow> this._totalRow)this._startRow=this._totalRow;
- this._priRow = this._startRow - this._showRow;
- this._nextRow = this._startRow + this._showRow;
- if(this._totalRow%this._showRow!=0)
- this._totalPage = this._totalRow/this._showRow+1;
- else this._totalPage = this._totalRow/this._showRow;
- this._endRow = this._showRow*(this._totalPage-1);
- this._nowPage = this._startRow/this._showRow+1;
- }
- public String getFontTypeOut(){
- StringBuffer outStrBuf=new StringBuffer();
- outStrBuf.append( " <tr> <td> ");
- outStrBuf.append( " 第 <font color=red> "+this._nowPage+ " </font> 页 / 共 <font color=red> "+this._totalPage+ " </font> 页 共 <font color=red> "+this._totalRow+ " </font> 条 </td> <td> ");
- if(this._startRow> 0){
- outStrBuf.append( " <a href=/ " "+this._selfPath+ "? "+this._paraStr+ "&statrow=0/ "> 首页 </a> /n ");
- outStrBuf.append( " <a href=/ " "+this._selfPath+ "? "+this._paraStr+ "&statrow= "+this._priRow+ "/ "> 上一页 </a> /n ");
- }else{
- outStrBuf.append( " <font color=#cccccc> 首页 上一页 </font> /n ");
- }
- outStrBuf.append( " </td> <td> ");
- if(this._nowPage <this._totalPage){
- outStrBuf.append( " <a href=/ " "+this._selfPath+ "? "+this._paraStr+ "&statrow= "+this._nextRow+ "/ "> 下一页 </a> /n ");
- outStrBuf.append( " <a href=/ " "+this._selfPath+ "? "+this._paraStr+ "&statrow= "+this._endRow+ "/ "> 尾页 </a> /n ");
- }else{
- outStrBuf.append( " <font color=#cccccc> 下一页 尾页 </font> /n ");
- }
- if(this._totalPage> 1){
- outStrBuf.append( " </td> <td> ");
- outStrBuf.append( " <script> function pageGoTo(objUrl,objcont,objValue){window.location= objUrl+(objValue*objcont);} </script> ");
- outStrBuf.append( "转到第 <SELECT name=/ "page/ " class=/ "select/ " οnchange=/ "pageGoTo( ' "+this._selfPath+ "? "+this._paraStr+ "&statrow= ', "+this._showRow+ ",this.value);/ "> ");
- for(int i=1;i <=this._totalPage;i++){
- outStrBuf.append( " <OPTION "+(this._nowPage==i? "selected ": " ")+ " value= "+(i-1)+ "> "+i+ " </OPTION> ");
- }
- outStrBuf.append( " </SELECT> 页 ");
- }
- outStrBuf.append( " </td> </tr> /n ");
- return outStrBuf.toString();
- }
- public String getInputTypeOut(){
- String outStr= " ";
- outStr+= " ";
- return outStr;
- }
- }
- 查询语句加上参数startRow,表示页数
- Jsp 分页代码3
- /**
- * Created by cyril.gu on Mar 24, 2007 12:00:57 PM
- * Email:zjjsgwm@163.com
- **/
- import java.util.List;
- public class PageList {
- private int currentPage = 1; //当前页码
- private int countPage = 0; //总页数
- private int pageRows = 0; //每页显示记录数
- private int countRows = 0; //总记录数
- //private int currentSize; //当前页记录数
- private List list; //结果集
- public String toString() {
- StringBuffer s = new StringBuffer();
- s.append( " <input type=/ "hidden/ " id=/ "pageList.currentPage/ " name=/ "pageList.currentPage/ "/> ");
- s.append( "第 "+currentPage+ "页/共 "+countPage+ "页 ");
- s.append( " 总 "+countRows+ "条记录 ");
- /**首页**/
- if(this.countPage> 1 && this.currentPage> 1)
- s.append( " <a href=/ "javascript:document.getElementById( 'pageList.currentPage ').value= '1 ';doPagination();/ "> 首页 </a> ");
- else
- s.append( " 首页 ");
- /**上一页**/
- if(this.currentPage> 1)
- s.append( " <a href=/ "javascript:document.getElementById( 'pageList.currentPage ').value= ' "+(this.currentPage-1)+ " ';doPagination();/ "> 上一页 </a> ");
- else
- s.append( " 上一页 ");
- /**下一页**/
- if(this.countPage> 1 && this.currentPage <this.countPage)
- s.append( " <a href=/ "javascript:document.getElementById( 'pageList.currentPage ').value= ' "+(this.currentPage+1)+ " ';doPagination();/ "> 下一页 </a> ");
- else
- s.append( " 下一页 ");
- /**尾页**/
- if(this.countPage> 1 && this.currentPage <this.countPage)
- s.append( " <a href=/ "javascript:document.getElementById( 'pageList.currentPage ').value= ' "+this.countPage+ " ';doPagination();/ "> 尾页 </a> ");
- else
- s.append( " 尾页 ");
- /**转到**/
- s.append( " 转至: <input type=/ "text/ " id=/ "pageList.toPage/ " name=/ "pageList.toPage/ " value=/ " "+this.currentPage+ "/ " style=/ "width:25px;/ "/> ");
- s.append( " <input type=/ "button/ " value=/ "GO/ " οnclick=/ "document.getElementById( 'pageList.currentPage ').value=document.getElementById( 'pageList.toPage ').value;doPagination();/ "/ style=/ "width:25px;/ "> ");
- s.append( " 每页显示: <input type=/ "text/ " id=/ "pageList.pageRows/ " name=/ "pageList.pageRows/ " value=/ " "+this.pageRows+ "/ " style=/ "width:25px;/ "/> ");
- s.append( " <input type=/ "button/ " value=/ "OK/ " οnclick=/ "doPagination();/ "/ style=/ "width:25px;/ "> ");
- return s.toString();
- }
- public int getCountPage() {
- return countPage;
- }
- public int getCountRows() {
- return countRows;
- }
- /**
- * 判断要跳至的页不能大于总页数
- * @return
- */
- public int getCurrentPage() {
- return currentPage;
- }
- /**
- * 当每页设置数为0时,自动调整为每页显示20
- * @return
- */
- public int getPageRows() {
- if(pageRows==0)
- pageRows = 20;
- return pageRows;
- }
- public void setCountPage(int countPage) {
- this.countPage = countPage;
- }
- public void setCountRows(int countRows) {
- this.countRows = countRows;
- }
- public void setCurrentPage(int currentPage) {
- this.currentPage = currentPage;
- }
- public void setPageRows(int pageRows) {
- this.pageRows = pageRows;
- }
- public List getList() {
- return list;
- }
- public void setList(List list) {
- this.list = list;
- }
- }
网上收集的分页代码
最新推荐文章于 2024-10-02 05:39:15 发布