Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2140769
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: Java

2012-03-14 14:55:15

    在JSP中执行一条SQL语句时,可能返回多条记录,如果所有的记录显示在同一页面,不仅效率低而且不易查阅,通常采用分页显示来解决这个问题。
通常而言,可以采用两种策略来实现分页:
  • 基于缓存(Cache-Based):这种方式一次性的将所有的记录取出来放到session或者其他的缓存机制中。这种方式的优点是:除了第一页外,后续的页面都能够很快访问到需要的数据。缺点是:第一页显示的时候可能很慢,因为需要等待取出所有的数据,而如果数据量比较大的话,比较慢。还有一个缺点是因为数据取出来以后都放在内存中,而如果同时访问的客户比较多的话,对内存的要求也比较高。
  • 基于查询(Query-Based):数据库中的数据根据需要取出。这种方式的优点是:第一页和后续的页面访问的时间差不多,将数据库访问分担到各页面了。缺点是:每次都需要从数据库中获取数据,造成频繁的数据库存取。

举例说明:

  1. 基于缓存的分页策略

     这个分页方法的核心是使用可滚动(Scrollable)的结果集,并且使用它的absolute()方法来获得指定范围的记录。例如,要取得第6-10的记录,可以调用absolute(6)方法,然后在此位置上,取出后面的5条记录即可。

处理数据库访问的JavaBean


 

点击(此处)折叠或打开

  1. package com.xdf.pagediv;
  2. import java.sql.*;
  3. public class CachedPageBean {
  4.     static String serverName="localhost";
  5.     static String sDBDriver="oracle.jdbc.driver.OracleDriver";
  6.     static String dbInstance="ORCL";
  7.     static String sConnStr="jdbc:oracle:thin:@"+serverName+":1521:"+dbInstance;
  8.     
  9.     static String dbUser="scott";
  10.     static String userPwd="tiger";
  11.     
  12.     /**
  13.      * 得到一个Connection对象
  14.      * @return java.sal.Connection
  15.      */
  16.     public static Connection getConnection(){
  17.         Connection conn=null;
  18.         try {
  19.             Class.forName(sDBDriver);
  20.             conn=DriverManager.getConnection(sConnStr,dbUser,userPwd);
  21.         } catch (ClassNotFoundException e) {
  22.             e.printStackTrace();
  23.         } catch (SQLException e) {
  24.             e.printStackTrace();
  25.         }
  26.         return conn;
  27.     }
  28.     
  29.     /**
  30.      * 关闭指定的结果集
  31.      * @param rs 要关闭的结果集
  32.      */
  33.     public static void closeResultSet(ResultSet rs){
  34.          if(rs!=null){
  35.              try{
  36.                  rs.close();
  37.              }catch(SQLException e){
  38.                 
  39.              }
  40.          }
  41.     }
  42.     
  43.     /**
  44.      * 关闭指定的Statement
  45.      * @param stmt 要关闭的Statement
  46.      */
  47.     public static void closeStatement(Statement stmt){
  48.         if(stmt!=null){
  49.             try{
  50.                 stmt.close();
  51.             }catch(SQLException e){}
  52.         }
  53.     }
  54.     
  55.     /**
  56.      * 关闭连接
  57.      * @param conn 要关闭的连接
  58.      */
  59.      public static void closeConnection(Connection conn){
  60.          if(conn!=null){
  61.              try{
  62.                  conn.close();
  63.              }catch(SQLException e){}
  64.          }
  65.      }
  66.      
  67.      /**
  68.       * 获得总的记录数目
  69.       */
  70.      public static int getRowNumber(){
  71.          Connection conn=getConnection();
  72.          int num=0;
  73.          try {
  74.             Statement stmt=conn.createStatement();
  75.             String sql="select count(*) as rowNumbers from emp";
  76.             ResultSet rs=stmt.executeQuery(sql);
  77.             rs.next();
  78.             num=rs.getInt("rowNumbers");
  79.         } catch (SQLException e) {
  80.             e.printStackTrace();
  81.         }finally{
  82.              closeConnection(conn);
  83.         }
  84.          return num;
  85.      }
  86.      
  87.      /**
  88.       * 根据指定的页面大小,获得页面数目
  89.       */
  90.      public static int getTotalPage(int pageSize){
  91.          int totalPage=1;
  92.          int tmpPage=0;
  93.          int rowNum=getRowNumber();
  94.          tmpPage=rowNum%pageSize;
  95.          if(tmpPage==0){
  96.              totalPage=rowNum/pageSize;
  97.          }else{
  98.              totalPage=(int)(Math.floor(rowNum/pageSize)+1);
  99.              //如果参数值已经等于某个整数,那么结果与该参数相同。

  100.          }
  101.          if(totalPage==0){
  102.              totalPage=1;
  103.          }
  104.          return totalPage;
  105.      }
  106.      
  107.     public static ResultSet getAllResults(){
  108.         Connection conn=null;
  109.         Statement stmt=null;
  110.         ResultSet rs=null;
  111.         String sql="select * from emp order by empno";
  112.          try{
  113.              conn=getConnection();
  114.              stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
  115.          }catch(SQLException e){
  116.              e.printStackTrace();
  117.          }
  118.          return rs;
  119.     }
  120.      /**
  121.       * 用于调试本类的方法
  122.       */
  123.      public static void main(String[] args) {
  124.          System.out.println(getTotalPage(14));
  125.     }
  126. }


 

点击(此处)折叠或打开

  1. <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
  2. <%@ page import="java.sql.*"%>
  3. <%@ page import="com.xdf.pagediv.*"%>
  4. <%!
  5.    ResultSet rs=null;
  6.    //页面大小

  7.    int pageSize=3;
  8.    //第几页

  9.    int pages=1;
  10.    //总页数

  11.    int totalPage=0;
  12.    
  13.    String str="";
  14.    public String showOnePage(ResultSet rs,int pages,int pageSize){
  15.         str="";
  16.         //将记录指针定位到相应的位置

  17.         try{
  18.           rs.absolute((pages-1)*pageSize+1);
  19.         }catch(SQLException e){
  20.             e.printStackTrace();
  21.         }
  22.         for(int i=1;i<=pageSize;i++){
  23.            str+=displayOneResult(rs);
  24.            try{
  25.              if(!rs.next()) break;
  26.            }catch(Exception e){
  27.       
  28.            }
  29.         }
  30.         return str;
  31.    }
  32.      //显示单行记录方法

  33.      public String displayOneResult(ResultSet rs){
  34.           String text="";
  35.           try{
  36.                text+="";
  37.                text+=""+rs.getInt("empno")+"";
  38.                text+=""+rs.getString("ename")+"";
  39.                text+=""+rs.getString("job")+"";
  40.                text+="";
  41.           }catch(Exception e){
  42.              e.printStackTrace();
  43.           }
  44.           return text;
  45.      }
  46. %>
  47. <%
  48.      try{
  49.           rs=CachedPageBean.getAllResults();
  50.      }catch(Exception e){
  51.           out.println("访问数据库出错!");
  52.      }
  53. %>
  54. <html>
  55.   <head>
  56.     <title>分页显示</title>
  57.   </head>
  58.   <body bgcolor="#FFFFFF">
  59.          <h2 align="center">分页显示</h2>
  60.         <hr>
  61.         <center>
  62.           <table border>
  63.              <tr bgcolor=lightblue>
  64.                <th>员工编号</th>
  65.                <th>员工姓名</th>
  66.                <th>职位</th>
  67.              </tr>
  68.              <%
  69.                totalPage =CachedPageBean.getTotalPage(5);
  70.                try{
  71.                     if(request.getParameter("Page")==null||request.getParameter("Page").equals(""))
  72.                     pages=1;
  73.                     else
  74.                     pages=Integer.parseInt(request.getParameter("Page"));
  75.                }catch(java.lang.NumberFormatException e){
  76.                    //处理用户从浏览器地址栏直接输入pages=ab等造成的异常

  77.                    pages=1;
  78.                }
  79.                if(pages<1) pages=1;
  80.                if(pages>totalPage) pages=totalPage;
  81.                 out.println(showOnePage(rs,pages,pageSize));
  82.              %>
  83.           </table>
  84.         <form action="cachePages.jsp" method="get">
  85.         <%
  86.             if(pages!=1){
  87.                 out.println("第一页");
  88.                 out.println("+(pages-1)+">上一页");
  89.             }
  90.           if(pages!=totalPage){
  91.               out.println("+(pages+1)+">下一页");
  92.               out.println("+totalPage+">最后一页");
  93.           }
  94.           rs.close();
  95.         %>
  96.         <p>输入页数:
  97.         <input type="text" name="Page" size="3" value="<%=pages%>">
  98.         <input type="submit" value="翻页">
  99.                      页数:<font color="red"><%=pages%>/<%=totalPage%></font>
  100.         </p>
  101.         </form>
  102.         </center>
  103.   </body>
  104. </html>

本案例没成功,待日后研究.....

参考资料

新东方Java工程师培训教材

阅读(2066) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~