zoukankan      html  css  js  c++  java
  • Java通用分页

    一. 要分页我们必须要有数据库,所以我们先准备下数据库,其数据库脚步如下:

  • --以下是创建数据库和数据库表以及向数据库插入数据  use master  
    Go  
    if exists(select * from sysdatabases where name='pagination')  
    drop database pagination  
    Go  
    create database pagination  
    Go  
    use pagination  
    Go  
    create table userInfo (  
        [userID] int identity(1,1) primary key not null,  
        [userName] nvarchar(50) not null,  
        [userPassword] nvarchar(50) not null,  
    )  
    Go  
    insert userInfo  values('xuyesheng','8888')  
    insert userInfo  values('jiaojiao','8888')  
    insert userInfo  values('administrator','888')  
    insert userInfo  values('xuyesheng1','123')  
    insert userInfo  values('xuyesheng2','123')  
    insert userInfo  values('xuyesheng3','123')  
    insert userInfo  values('xuyesheng4','123')  
    insert userInfo  values('xuyesheng5','123')  
    insert userInfo  values('xuyesheng6','123')  
    Go  
    select * from userInfo

    二: 通用分页的存储过程,如下:

        ---------------创建存储过程--------------  
        Go  
        set ANSI_NULLS ON  
        set QUOTED_IDENTIFIER ON  
        go  
        ------------------------------------  
        --  
        --用途:用于需要分页显示的数据  
        --时间:2009年08月22日  
        --描述:通用的存储过程分页程序  
        --  
        -------------------------------------  
        create PROCEDURE [dbo].[GetData]  
        @tblName varchar(255), -- 表名  
        @fldName varchar(255), -- 字段名  
        @OrderfldName varchar(255), -- 排序字段名  
        @PageSize int = 10, -- 页尺寸  
        @PageIndex int = 1, -- 页码  
        @IsCount bit = 0, -- 返回记录总数, 非 0 值则返回  
        @OrderType bit = 0, -- 设置排序类型, 非 0 值则降序  
        @strWhere varchar(1000) = '' -- 查询条件 (注意: 不要加 where)  
        AS  
        declare @strSQL varchar(6000) -- 主语句  
        declare @strTmp varchar(500) -- 临时变量  
        declare @strOrder varchar(400) -- 排序类型  
        if @OrderType != 0  
        begin  
          set @strTmp = '<(select min'  
          set @strOrder = ' order by [' + @OrderfldName +'] desc'  
        end  
        else  
        begin  
          set @strTmp = '>(select max'  
          set @strOrder = ' order by [' + @OrderfldName +'] asc'  
        end  
          set @strSQL = 'select top ' + str(@PageSize) + ' ' + @fldName + ' from ['  
          + @tblName + '] where [' + @OrderfldName + ']' + @strTmp + '(['  
          + @OrderfldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['  
          + @OrderfldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'  
          + @strOrder  
          if @strWhere != ''  
          set @strSQL = 'select top ' + str(@PageSize) + ' ' + @fldName + ' from ['  
          + @tblName + '] where [' + @OrderfldName + ']' + @strTmp + '(['  
          + @OrderfldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['  
          + @OrderfldName + '] from [' + @tblName + '] where ' + @strWhere + ' '  
          + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder  
          if @PageIndex = 1  
          begin  
           set @strTmp = ''  
           if @strWhere != ''  
              set @strTmp = ' where ' + @strWhere  
              set @strSQL = 'select top ' + str(@PageSize) + ' ' + @fldName + ' from ['  
              + @tblName + ']' + @strTmp + ' ' + @strOrder  
          end  
          if @IsCount != 0  
          begin  
               if @strWhere != ''  
                set @strSQL = 'select count(' + @OrderfldName + ') as Total from [' + @tblName + ']'+ ' where ' + @strWhere    
                else  
                set @strSQL = 'select count(' + @OrderfldName + ') as Total from [' + @tblName + ']'      
          end  
        exec (@strSQL)  
        --测试下  
        Go  
        ----参数说明exec [GetData] '表明','查找的列名* 表示查找所有信息','主键',页大小,第几页,非  
        --表示返回记录数,[排序类型,非则降序排列],条件  
        --得到分页的数据  
        exec [GetData] 'userInfo','*','userID',5,1,0,0,null  
        --得到总共的条数  
        exec [GetData] 'userInfo','*','userID',5,1,1,0,null  
        --根据条件查询  
        exec [GetData] 'userInfo','*','userID',5,1,0,0,' userID like ''%2%'' '

    存储过程我们有了我们只要给一下几个参数就OK了

    @tblName varchar  -- 表名
    @fldName varchar  --
     字段名
    @OrderfldName     --
     排序字段名
    @PageSize int     --
     页尺寸
    @PageIndex int    --
     页码
    @IsCount bit      --
     返回记录总数, 非 0 值则返回
    @OrderType bit    --
     设置排序类型, 非 0 值则降序
    @strWhere varchar --
     查询条件 (注意: 不要加 where)


    三 通用包

    到这里我们先不用急,先将一下三个Java类(Pagination.java Call.java AutoSetData.java)封装一下,然后打成JAR包,以后我们直接导入JAR包即可

    Pagination.java

    存储过程我们有了我们只要给一下几个参数就OK了

    @tblName varchar  -- 表名
    @fldName varchar  --
     字段名
    @OrderfldName     --
     排序字段名
    @PageSize int     --
     页尺寸
    @PageIndex int    --
     页码
    @IsCount bit      --
     返回记录总数, 非 0 值则返回
    @OrderType bit    --
     设置排序类型, 非 0 值则降序
    @strWhere varchar --
     查询条件 (注意: 不要加 where)

    到这里我们先不用急,先将一下三个Java类(Pagination.java Call.java AutoSetData.java)封装一下,然后打成JAR包,以后我们直接导入JAR包即可

    Pagination.java

     

    1. import java.util.List;  
    2. public class Pagination {  
    3.     // 总共的数据量  
    4.     private int totle;  
    5.     // 每页显示多少条  
    6.     private int pageSize;  
    7.     // 共有多少页  
    8.     private int totlePage;  
    9.     // 当前是第几页  
    10.     private int index;  
    11.     // 数据  
    12.     private List data;  
    13.     // 连接路径  
    14.     private String path;  
    15.     public void setTotle(int totle) {  
    16.         this.totle = totle;  
    17.     }  
    18.     public void setPageSize(int pageSize) {  
    19.         this.pageSize = pageSize;  
    20.     }  
    21.     public void setIndex(int index) {  
    22.         this.index = index;  
    23.     }  
    24.     public void setPath(String path) {  
    25.         this.path = path;  
    26.     }  
    27.     public int getTotle() {  
    28.         return totle;  
    29.     }  
    30.     public int getPageSize() {  
    31.         return pageSize;  
    32.     }  
    33.     public int getTotlePage() {  
    34.         return (this.totle + this.pageSize - 1) / this.pageSize;  
    35.     }  
    36.     public int getIndex() {  
    37.         return index;  
    38.     }  
    39.     public List getData() {  
    40.         return data;  
    41.     }  
    42.     public void setData(List data) {  
    43.         this.data = data;  
    44.     }  
    45.     public String getPageDisplay() {  
    46.         StringBuffer displayInfo = new StringBuffer();  
    47.         if (index == 0 || pageSize == 0) {  
    48.             displayInfo.append("没有分页的信息!");  
    49.         } else {  
    50.             displayInfo.append("<div class='pager'>");  
    51.             displayInfo.append("共" + totle + "条记录每页<span style="color:#FF0000" mce_style="color:#FF0000">" + pageSize  
    52.                     + "</span>条");  
    53.             displayInfo.append("第<span style="color:#FF0000" mce_style="color:#FF0000">" + index  
    54.                     + "</span>页/共"  
    55.                     + this.getTotlePage() + "页");  
    56.             // 判断如果当前是第一页 则“首页”和“第一页”失去链接  
    57.             if (index == 1) {  
    58.                 displayInfo.append("  首页 ");  
    59.                 displayInfo.append("上一页 ");  
    60.             } else {  
    61.                 displayInfo.append("  <a href="" + path  
    62.                         + "index=1" mce_href="" + path  
    63.                         + "index=1">首页</a> ");  
    64.                 displayInfo.append("<a href="" + path + "index=" + (index - 1)  
    65.                         + "" mce_href="" + path + "index=" + (index - 1)  
    66.                         + "">上一页</a> ");  
    67.             }  
    68.             if (index >= this.getTotlePage()) {  
    69.                 displayInfo.append("下一页 ");  
    70.                 displayInfo.append("最后一页 ");  
    71.             } else {  
    72.                 displayInfo.append("<a href="" + path + "index=" + (index + 1)  
    73.                         + "" mce_href="" + path + "index=" + (index + 1)  
    74.                         + "">下一页</a> ");  
    75.                 displayInfo.append("<a href="" + path + "index="  
    76.                         + this.getTotlePage() + "" mce_href="" + path + "index="  
    77.                         + this.getTotlePage() + "">最后一页</a> ");  
    78.             }  
    79.             displayInfo.append("</div>");  
    80.         }  
    81.         return displayInfo.toString();  
    82.     }  
    83. }    
     

    Pagination.java文件源码我们有了,下面的是Call.java类的源码

     

    1. import java.sql.Connection;  
    2. import java.sql.DriverManager;  
    3. import java.sql.ResultSet;  
    4. import java.sql.SQLException;  
    5. import java.util.ArrayList;  
    6. import java.util.Collection;  
    7. import java.util.Iterator;  
    8. import java.util.List;  
    9. public class Call {  
    10.     private AutoSetData auto = new AutoSetData();  
    11.      
    12.     public List execProcedure(String driver, String url, String userName,  
    13.             String pwd, Object[] ob, Class c) {  
    14.         try {  
    15.             Class.forName(driver);  
    16.             Connection conn = DriverManager.getConnection(url, userName, pwd);  
    17.             String sql = "exec GetData ?,?,?,?,?,?,?,null";  
    18.             List list = new ArrayList();  
    19.             // Ltest是我测试用类,实际操作请注入相关对象,支持set,get,is,read,writer为前缀数据对,更多请继续添加。  
    20.             Collection collection = auto.get(conn, c.newInstance().getClass(),  
    21.                     sql, ob);  
    22.             for (Iterator it = collection.iterator(); it.hasNext();) {  
    23.                 Object obj = c.newInstance();  
    24.                 list.add(it.next());  
    25.             }  
    26.             return list;  
    27.         } catch (Exception e) {  
    28.             e.printStackTrace();  
    29.         }  
    30.         return null;  
    31.     }  
    32.      
    33. }  
     

    AutoSetData.java 自动将数据封装到实体类中

     

    1. import java.lang.reflect.Method;  
    2. import java.lang.reflect.Modifier;  
    3. import java.sql.CallableStatement;  
    4. import java.sql.Connection;  
    5. import java.sql.ResultSet;  
    6. import java.sql.ResultSetMetaData;  
    7. import java.sql.SQLException;  
    8. import java.util.ArrayList;  
    9. import java.util.Collection;  
    10. public class AutoSetData {  
    11.      
    12.     private Object[] beanMatch(Class clazz, String beanProperty) {  
    13.         Object[] result = new Object[2];  
    14.         char beanPropertyChars[] = beanProperty.toCharArray();  
    15.         beanPropertyChars[0] = Character.toUpperCase(beanPropertyChars[0]);  
    16.         String s = new String(beanPropertyChars);  
    17.         String names[] = { ("set" + s).intern(), ("get" + s).intern(),  
    18.                 ("is" + s).intern(), ("write" + s).intern(),  
    19.                 ("read" + s).intern() };  
    20.         Method getter = null;  
    21.         Method setter = null;  
    22.         Method methods[] = clazz.getMethods();  
    23.         for (int i = 0; i < methods.length; i++) {  
    24.             Method method = methods[i];  
    25.             // 只取公共字段  
    26.             if (!Modifier.isPublic(method.getModifiers()))  
    27.                 continue;  
    28.             String methodName = method.getName().intern();  
    29.             for (int j = 0; j < names.length; j++) {  
    30.                 String name = names[j];  
    31.                 if (!name.equals(methodName))  
    32.                     continue;  
    33.                 if (methodName.startsWith("set")  
    34.                         || methodName.startsWith("read"))  
    35.                     setter = method;  
    36.                 else  
    37.                     getter = method;  
    38.             }  
    39.         }  
    40.         result[0] = getter;  
    41.         result[1] = setter;  
    42.         return result;  
    43.     }  
    44.      
    45.     private void beanRegister(Object object, String beanProperty, String value) {  
    46.         Object[] beanObject = beanMatch(object.getClass(), beanProperty);  
    47.         Object[] cache = new Object[1];  
    48.         Method getter = (Method) beanObject[0];  
    49.         Method setter = (Method) beanObject[1];  
    50.         try {  
    51.             // 通过get获得方法类型  
    52.             String methodType = getter.getReturnType().getName();  
    53.             if (methodType.equalsIgnoreCase("long")) {  
    54.                 cache[0] = new Long(value);  
    55.                 setter.invoke(object, cache);  
    56.             } else if (methodType.equalsIgnoreCase("int")  
    57.                     || methodType.equalsIgnoreCase("integer")) {  
    58.                 cache[0] = new Integer(value);  
    59.                 setter.invoke(object, cache);  
    60.             } else if (methodType.equalsIgnoreCase("short")) {  
    61.                 cache[0] = new Short(value);  
    62.                 setter.invoke(object, cache);  
    63.             } else if (methodType.equalsIgnoreCase("float")) {  
    64.                 cache[0] = new Float(value);  
    65.                 setter.invoke(object, cache);  
    66.             } else if (methodType.equalsIgnoreCase("double")) {  
    67.                 cache[0] = new Double(value);  
    68.                 setter.invoke(object, cache);  
    69.             } else if (methodType.equalsIgnoreCase("boolean")) {  
    70.                 cache[0] = new Boolean(value);  
    71.                 setter.invoke(object, cache);  
    72.             } else if (methodType.equalsIgnoreCase("java.lang.String")) {  
    73.                 cache[0] = value;  
    74.                 setter.invoke(object, cache);  
    75.             } else if (methodType.equalsIgnoreCase("java.io.InputStream")) {  
    76.             } else if (methodType.equalsIgnoreCase("char")) {  
    77.                 cache[0] = (Character.valueOf(value.charAt(0)));  
    78.                 setter.invoke(object, cache);  
    79.             }  
    80.         } catch (Exception e) {  
    81.             e.printStackTrace();  
    82.         }  
    83.     }  
    84.      
    85.     public Collection get(final Connection connection, final Class clazz,  
    86.              String sql,Object[] obj) {  
    87.         // 创建PreparedStatement  
    88.         CallableStatement  ptmt = null;  
    89.         // 创建resultset  
    90.         ResultSet rset = null;  
    91.         // 创建collection  
    92.         Collection collection = null;  
    93.         try {  
    94.             // 赋予实例  
    95.             ptmt = connection.prepareCall(sql);  
    96.             for (int i = 1; i <= obj.length; i++) {  
    97.                 ptmt.setObject(i,obj[i-1]);  
    98.             }  
    99.             rset = ptmt.executeQuery();  
    100.             collection = get(rset, clazz);  
    101.         } catch (SQLException e) {  
    102.             System.err.println(e.getMessage());  
    103.         } finally {  
    104.             try {  
    105.                 // 关闭rs并释放资源  
    106.                 if (rset != null) {  
    107.                     rset.close();  
    108.                     rset = null;  
    109.                 }  
    110.                 // 关闭ps并释放资源  
    111.                 if (ptmt != null) {  
    112.                     ptmt.close();  
    113.                     ptmt = null;  
    114.                 }  
    115.             } catch (SQLException e) {  
    116.                 System.err.println(e.getMessage());  
    117.             }  
    118.         }  
    119.         return collection;  
    120.     }  
    121.     public Collection get(final ResultSet result, final Class clazz) {  
    122.         // 创建collection  
    123.         Collection collection = null;  
    124.         try {  
    125.             ResultSetMetaData rsmd = result.getMetaData();  
    126.             // 获得数据列数  
    127.             int cols = rsmd.getColumnCount();  
    128.             // 创建等同数据列数的arraylist类型collection实例  
    129.             collection = new ArrayList(cols);  
    130.             // 遍历结果集  
    131.             while (result.next()) {  
    132.                 // 创建对象  
    133.                 Object object = null;  
    134.                 try {  
    135.                     // 从class获得对象实体  
    136.                     object = clazz.newInstance();  
    137.                 } catch (Exception e) {  
    138.                 }  
    139.                 // 循环每条记录  
    140.                 for (int i = 1; i <= cols; i++) {  
    141.                     beanRegister(object, rsmd.getColumnName(i), result  
    142.                             .getString(i));  
    143.                 }  
    144.                 // 将数据插入collection  
    145.                 collection.add(object);  
    146.             }  
    147.         } catch (SQLException e) {  
    148.             System.err.println(e.getMessage());  
    149.         } finally {  
    150.         }  
    151.         return collection;  
    152.     }  
    153. }  
     

    看这里我们引入了jstl.jar standard.jar sqljdbc.jar pagination.jar四个jar包 缺一不可奥。

    下面我们创建一个实体类,代码如下: 

    1. public class UserInfo {  
    2.     private int userID;  
    3.     private String userName;  
    4.     private String userPassword;  
    5.  public int getUserID() {  
    6.   return userID;  
    7.  }  
    8.  public void setUserID(int userID) {  
    9.   this.userID = userID;  
    10.  }  
    11.  public String getUserName() {  
    12.   return userName;  
    13.  }  
    14.  public void setUserName(String userName) {  
    15.   this.userName = userName;  
    16.  }  
    17.  public String getUserPassword() {  
    18.   return userPassword;  
    19.  }  
    20.  public void setUserPassword(String userPassword) {  
    21.   this.userPassword = userPassword;  
    22.  }  
    23.      
    24. }  
     

     

    实体类我们创建完毕,现在我们创建servlet:

     

    1. import java.io.IOException;  
    2. import java.util.ArrayList;  
    3. import java.util.List;  
    4. import javax.servlet.ServletException;  
    5. import javax.servlet.http.HttpServlet;  
    6. import javax.servlet.http.HttpServletRequest;  
    7. import javax.servlet.http.HttpServletResponse;  
    8. import com.ant.util.Call;  
    9. import com.ant.util.Pagination;  
    10. import com.xuyesheng.entity.UserInfo;  
    11. public class PageServlet extends HttpServlet {  
    12.    
    13.  public void doGet(HttpServletRequest request, HttpServletResponse response)  
    14.    throws ServletException, IOException {  
    15.   this.doPost(request, response);  
    16.  }  
    17.  public void doPost(HttpServletRequest request, HttpServletResponse response)  
    18.    throws ServletException, IOException {  
    19.   //取得jsp页面传递来的页数,参数名 index 不可更改  
    20.   String index = request.getParameter("index");  
    21.   int num = 0;  
    22.   if (index == null) {  
    23.    num = 1;  
    24.   } else {  
    25.    num = Integer.parseInt(index);  
    26.   }  
    27.   //创建封装数据类的对象 call  
    28.   Call call = new Call();  
    29.   //创建数组存储 存储过程的参数  
    30.   Object obj[] = { "userInfo""*""userID"5, num+""0+""0+"" };  
    31.   //调用执行存储过程的方法  
    32.   List li = call.execProcedure(  
    33.     "com.microsoft.sqlserver.jdbc.SQLServerDriver",  
    34.     "jdbc:sqlserver://localhost:1433;databaseName=pagination",  
    35.     "sa""as", obj, UserInfo.class);  
    36.   //保存用户名  
    37.   List<String> list = new ArrayList<String>();  
    38.   //便利集合  
    39.   for (int i = 0; i < li.size(); i++) {  
    40.    UserInfo ui = (UserInfo) li.get(i);  
    41.    list.add(ui.getUserName());  
    42.    list.add(ui.getUserPassword());  
    43.   }  
    44.   //创建 分页对象  
    45.   Pagination p = new Pagination();  
    46.   //设置页数  
    47.   p.setIndex(num);  
    48.   //设置页大小  
    49.   p.setPageSize(Integer.parseInt(obj[3].toString()));  
    50.   //设置总共的条数  
    51.   p.setTotle(call.getTotle());  
    52.   //设置数据  
    53.   p.setData(list);  
    54.   //跳转的路径  
    55.   p.setPath("page.do?");  
    56.   request.setAttribute("page", p);  
    57.   request.getRequestDispatcher("index.jsp").forward(request, response);  
    58.  }  
    59. }  
       

     

    到这里我们就差一个页面了:

    页面代码如下: 

    1. <%@ page language="java"  pageEncoding="GBK"%>  
    2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
    3. <html>  
    4.   <head>  
    5.     <title>java通用分页显示数据</title>  
    6.   </head>  
    7.   <body>  
    8.  <table width="507" height="160" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#999900">  
    9.          <tr>  
    10.            <td  height="40" align="center" valign="middle" bgcolor="#FF9999"><h2>许业生用java实现通用分页功能</h2></td>  
    11.          </tr>  
    12.          <tr>  
    13.            <td  height="35" align="center" valign="middle" bgcolor="#FF9999"><h3>用户名</h3></td>  
    14.            
    15.          </tr>  
    16.           <c:forEach items="${requestScope.page.data}" var="li" >  
    17.          <tr>  
    18.            <td height="35" align="center" valign="middle" bgcolor="#CC99CC" >  
    19.       <c:out value="${li}"/>  
    20.     </td>  
    21.          </tr>  
    22.          </c:forEach>  
    23.          <tr>  
    24.            <td height="40"  align="center" valign="middle" ><c:out value="${requestScope.page.pageDisplay}" escapeXml="false"/></td>  
    25.          </tr>  
    26.        </table>  
    27.   </body>  
    28. </html>  
     

    其中web.xml文件中的servlet的路径配置如下:

     

    1.   <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app version="2.4"  
    3.  xmlns="http://java.sun.com/xml/ns/j2ee"  
    4.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    5.  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
    6.  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
    7.   <servlet>  
    8.     <description>通用分页Servlet</description>  
    9.     <servlet-name>PageServlet</servlet-name>  
    10.     <servlet-class>com.xuyesheng.servlet.PageServlet</servlet-class>  
    11.   </servlet>  
    12.   <servlet-mapping>  
    13.     <servlet-name>PageServlet</servlet-name>  
    14.     <url-pattern>/page.do</url-pattern>  
    15.   </servlet-mapping>  
    16.   <welcome-file-list>  
    17.     <welcome-file>index.jsp</welcome-file>  
    18.   </welcome-file-list>  
    19. </web-app>  
     

    到这里我们的通用分页已经结束了,该怎么访问呢?

    呵呵  大家肯定比我知道啦!http://localhost:8080/pagination/page.do

    大功告成!谢谢给位光临!

     

    然后我们将刚才的三个.java文件打成JAR包,下次我们用的时候直接导入这个jar包就行了

    四:项目使用

    现在我们新建一个项目测试一下如何使用:

    在我们创建项目的时候给项目添加jstl标签支持,我们在页面会用到,项目框架如下:

查看全文
  • 相关阅读:
    初创团队的技术选择
    敏捷大数据流程
    深入分析Java Web技术内幕(修订版)
    重构大数据统计
    Robot Framework学习笔记(十一)------ 分层设计
    Robot Framework学习笔记(十)------Selenium2Library库
    Robot Framework学习笔记(九)------创建资源和用户关键字
    Robot Framework学习笔记(八)------ride标签使用
    robotframework学习笔记(七)------筛选执行用例
    chromedriver与chrome版本映射列表
  • 原文地址:https://www.cnblogs.com/daichangya/p/12959055.html
  • Copyright © 2011-2022 走看看