JSP 连接池技术实现分页(源码贴出来了)

在工作目录下META-INF中创建一个context.xml,其代码如下:

<Context> 

<Resource

name="jdbc/zihan" //随便自己的命名

type="javax.sql.DataSource"

password="yd"

driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"

maxIdle="2"

maxWait="5000"

username="sa"

url="jdbc:microsoft:sqlserver://localhost;DatabaseName=news"

maxActive="10"/>

</Context>

在这里配置移植性强。

二、

然后创建JDBC.java文件,其代码如下:

package com.mwq.database;

 

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.sql.DataSource;

 

/**

 

 * @author mwq

 *

 */

public class JDBC {

 

           protected Connection conn;

 

           protected Statement stmt;

 

           protected PreparedStatement prpdStmt;

 

           protected CallableStatement cablStmt;

 

           protected ResultSet rs;

           static DataSource ds;

 

           static {

                     try {

                                Context initCtx=new InitialContext();

                                ds=(DataSource)initCtx.lookup("java:comp/env/jdbc/zihan");

                     } catch (NamingException e) {

                                // TODO Auto-generated catch block

                                e.printStackTrace();

                     }

           }

 

           public boolean openConn(boolean autoCommit) {

                     boolean isOpen = true;

                     try {

                                conn = ds.getConnection();

                                if (!autoCommit)

                                           conn.setAutoCommit(false);

                     } catch (SQLException e) {

                                isOpen = false;

                                System.out.println("------ 在创建数据库连接时抛出异常,内容如下:");

                                e.printStackTrace();

                     }

                     return isOpen;

           }

 

           public boolean closeConn() {

                     boolean isCommit = true;

                     try {

                                conn.commit();

                     } catch (SQLException e) {

                                isCommit = false;

                                System.out.println("------ 在提交数据库事务时抛出异常,内容如下:");

                                e.printStackTrace();

                                try {

                                           conn.rollback();

                                } catch (SQLException e1) {

                                           System.out.println("------ 在回滚数据库事务时抛出异常,内容如下:");

                                           e1.printStackTrace();

                                }

                     } finally {

                                try {

                                           conn.close();

                                } catch (SQLException e) {

                                           System.out.println("------ 在关闭数据库连接时抛出异常,内容如下:");

                                           e.printStackTrace();

                                }

                     }

                     return isCommit;

           }

 

}

三、创建存放数据的OperateTb.java文件

package com.mwq.database;

 

import java.util.ArrayList;

import java.util.List;

 

public class OperateTb extends JDBC {

 

           public List<Object[]> selectBySQL(String sql) {

                     List<Object[]> notes = new ArrayList<Object[]>();

                     this.openConn(true);

                     try {

                                this.stmt = conn.createStatement();

                                this.rs = this.stmt.executeQuery(sql); // 通过父类的属性操作数据库

                                int l = rs.getMetaData().getColumnCount(); // 获得数据表的列数

                                while (rs.next()) { // 通过循环将记录保存到List

                                           Object[] note = new Object[l];

                                           for (int i = 0; i < l; i++) {

                                                     note[i] = rs.getObject(i + 1);

                                           }

                                           notes.add(note);

                                }

                                this.rs.close();

                                this.stmt.close();

                     } catch (Exception e) {

                                System.out.println("------ 在检索记录时抛出异常,内容如下:");

                                e.printStackTrace();

                     }

                     this.closeConn(); // 调用父类的关闭数据库连接的方法

                     return notes;

           }

 

 

}

分页的Pagination.java文件

package com.mwq.tool;

 

import java.util.ArrayList;

import java.util.List;

 

/**

 * @作者紫寒11202010-05-23

 */

 

public class Pagination {

 

           private int currentPage; // 当前页

 

           private int totalPages; // 总页数

 

           private int pageRows; // 每页记录数

 

           private int totalRows; // 总记录数

 

           private int pageStartRow; // 每页开始记录

 

           private int pageEndRow; // 每页结束记录

 

           private boolean hasPreviousPage;// 是否有上一页

 

           private boolean hasNextPage; // 是否有下一页

 

           private List<Object[]> totalList; // 要分页的数据

 

           public Pagination() {

           }

 

           // 初始化分页信息

           public void initPageBean(List<Object[]> totalList, int pageRows) {

                     this.totalList = totalList;

                     this.pageRows = pageRows;

                     this.totalRows = totalList.size();

                     this.currentPage = 1;

                     // 计算总页数

                     if ((totalRows % pageRows) == 0) {

                                totalPages = totalRows / pageRows;

                                if (this.totalRows == 0)

                                           this.totalPages = 1;

                     } else {

                                totalPages = totalRows / pageRows + 1;

                     }

                     // 默认无上一页

                     this.hasPreviousPage = false;

                     // 判断是否有下一页

                     if (currentPage == totalPages) {

                                hasNextPage = false;

                     } else {

                                hasNextPage = true;

                     }

                     // 默认第一页开始的记录数为1

                     this.pageStartRow = 1;

                     // 确定第一页结束的记录数

                     if (totalRows < pageRows) {

                                this.pageEndRow = totalRows;

                     } else {

                                this.pageEndRow = pageRows;

                     }

           }

 

           // 获得当前页信息

           public List<Object[]> getCurrentPageList() {

                     if (currentPage * pageRows < totalRows) {

                                pageEndRow = currentPage * pageRows;

                                pageStartRow = pageEndRow - pageRows;

                     } else {

                                pageEndRow = totalRows;

                                pageStartRow = pageRows * (totalPages - 1);

                     }

                     List<Object[]> pageList = new ArrayList<Object[]>(pageEndRow

                                           - pageStartRow + 1);

                     if (totalRows != 0) {

                                for (int i = pageStartRow; i < pageEndRow; i++) {

                                           pageList.add(totalList.get(i));

                                }

                     }

                     return pageList;

           }

 

           // 获得上一页信息

           public List<Object[]> getPreviousPageList() {

                     currentPage = currentPage - 1;

                     if (currentPage < 1)

                                currentPage = 1;

                     if (currentPage >= totalPages) {

                                hasNextPage = false;

                     } else {

                                hasNextPage = true;

                     }

                     if ((currentPage - 1) > 0) {

                                hasPreviousPage = true;

                     } else {

                                hasPreviousPage = false;

                     }

                     List<Object[]> pageList = this.getCurrentPageList();

                     return pageList;

           }

 

           // 获得下一页信息

           public List<Object[]> getNextPageList() {

                     currentPage = currentPage + 1;

                     if (currentPage > totalPages)

                                currentPage = totalPages;

                     if ((currentPage - 1) > 0) {

                                hasPreviousPage = true;

                     } else {

                                hasPreviousPage = false;

                     }

                     if (currentPage >= totalPages) {

                                hasNextPage = false;

                     } else {

                                hasNextPage = true;

                     }

                     List<Object[]> pageList = this.getCurrentPageList();

                     return pageList;

           }

 

           // 获得指定页信息

           public List<Object[]> getAppointPageList(int currentPage) {

                     this.currentPage = currentPage;

                     if (currentPage > this.totalPages)

                                this.currentPage = this.totalPages;

                     if (currentPage < 1)

                                this.currentPage = 1;

                     if (this.currentPage > 1) {

                                this.hasPreviousPage = true;

                     } else {

                                this.hasPreviousPage = false;

                     }

                     if (this.currentPage < this.totalPages) {

                                this.hasNextPage = true;

                     } else {

                                this.hasNextPage = false;

                     }

                     List<Object[]> pageList = this.getCurrentPageList();

                     return pageList;

           }

 

           // 返回当前页

           public int getCurrentPage() {

                     return currentPage;

           }

 

           // 返回每页记录数

           public int getPageRows() {

                     return pageRows;

           }

 

           // 返回当前页开始记录

           public int getPageStartRow() {

                     return pageStartRow;

           }

 

           // 返回当前页结束记录

           public int getPageEndRow() {

                     return pageEndRow;

           }

 

           // 返回总页数

           public int getTotalPages() {

                     return totalPages;

           }

 

           // 返回总记录数

           public int getTotalRows() {

                     return totalRows;

           }

 

           // 返回是否有上一页

           public boolean isHasPreviousPage() {

                     return hasPreviousPage;

           }

 

           // 返回是否有下一页

           public boolean isHasNextPage() {

                     return hasNextPage;

           }

 

}

实现分页的index.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>

<jsp:useBean id="optb" class="com.mwq.database.OperateTb" scope="page"/>

<jsp:useBean id="pagination" class="com.mwq.tool.Pagination" scope="session"/>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <title>利用数据分页BeanResultSet结果集进行分页</title>

  </head>

 

  <link rel="stylesheet" href="css/style.css">

 

 

  <script language="javascript" type="">

  <!--

  function checkPage(formName){

    if (formName.requestPage.value==""){

      alert("请填写欲跳转页码!");

      formName.requestPage.focus();

      return false;

    }

    if (isNaN(formName.requestPage.value)){

      alert("欲跳转页码必须为数值!");

      formName.requestPage.value="";

      formName.requestPage.focus();

      return false;

    }

  }

  //-->

  </script>

 

<body topmargin="0">

<table width="100%"  border="0" cellspacing="0" cellpadding="0">

  <tr>

    <td width="11%"></td>

    <td width="78%"></td>

    <td width="11%"></td>

  </tr>

  <tr>

    <td>&nbsp;</td>

    <td bgcolor="#CCFFFF"><table width="100%"  border="0" cellspacing="0" cellpadding="0">

      <tr>

        <td>&nbsp;</td>

      </tr>

      <tr>

        <td align="center"><font size="2"><b>利用数据分页BeanResultSet结果集进行分页</b></font></td>

      </tr>

      <tr>

        <td>&nbsp;</td>

      </tr>

      <%

      List<Object[]> pageList=null;

      if(request.getParameter("requestPage")==null){

          List<Object[]> totalList=optb.selectBySQL("select * from news");

          pagination.initPageBean(totalList,5);

          pageList=pagination.getCurrentPageList();

      }else{

      String requestPage=request.getParameter("requestPage");

      if(requestPage.equals("previousPage")){

              pageList=pagination.getPreviousPageList();           

      }elseif(requestPage.equals("nextPage")){

              pageList=pagination.getNextPageList();           

      }

      else{

           int appointPage=Integer.valueOf(requestPage);

              pageList=pagination.getAppointPageList(appointPage);

      }

      }

     

      %>

      <tr>

        <td align="center"><table width="80%" border="1" cellspacing="0" cellpadding="4">

          <tr align="center" bgcolor="yellow">

            <td>NewsID</td>

            <td>Title</td>

            <td>body</td>

            <td>hits</td>

            <td>shijain</td>

            <td>学历</td>

            <td>籍贯</td>

          </tr>

          <%

          for(int m=0;m<pageList.size();m++){

            

                if((m+1)%2==0)

                        out.println("<tr align=center bgcolor=#E6E6E6 >");

               else

               out.println("<tr align=center bgcolor=white>");

               %>

             

              <%

            Object[] note=pageList.get(m);

              out.println("<td>"+note[0]+"</td>");

              out.println("<td>"+note[1]+"</td>");

              out.println("<td>"+note[2]+"</td>");

              out.println("<td>"+note[3]+"</td>");

              out.println("<td>"+note[4]+"</td>");

              out.println("<td>"+note[5]+"</td>");

              out.println("<td align='left'>"+note[6]+"</td>");

              %>

              </tr>

              <%

          }

          %>

          </table>

<form action="index.jsp" method="post" name="page" onsubmit="return checkPage(page)">

 <tralign="right">

        <td>共有<font color="red" size="1">&nbsp;<%=pagination.getTotalRows() %>&nbsp;</font>条记录,

        当前是第<font color="red" size="1">&nbsp;<%=pagination.getCurrentPage()+"/"+pagination.getTotalPages() %>&nbsp;</font>&nbsp;

        <a href="index.jsp">首页</a>   &nbsp;

        <%if(pagination.isHasPreviousPage())out.print("<a href='index.jsp?requestPage=previousPage'>上一页</a>&nbsp;"); %>

        <%if(pagination.isHasNextPage())out.print("&nbsp;<a href='index.jsp?requestPage=nextPage'>下一页</a>&nbsp;"); %>&nbsp;

        <input type="text" name="requestPage" size="3" maxlength="2">&nbsp;&nbsp;

        <input type="submit" value="转到>>">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>

      </tr>

</form>

        </td>

      </tr>

      <tr>

        <td>&nbsp;</td>

      </tr>

    </table></td>

    <td>&nbsp;</td>

  </tr>

</table>

</body>

 

</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值