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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章