本文執行個體講述了jsp+servlet+javabean實現資料分頁方法。分享給大家供大家參考,具體如下:
這裡秉著且行且記的心態,記錄下學習過程,學得快忘得快,生怕遺忘,以備日後使用。
用到的部分代碼是自己在網上尋找,並自己修改,加上自己的理解。也不知道算不算原創,只做自己學習記錄。
使用相關:PostgreSQL資料庫、dom4j、JSP、Servlet
一、首先是工程格局,來個全域視圖方便讀者與自己查看與使用
思路為:
以config.xml檔案記錄配置資訊,以方便資料庫更改,方便移植與重用。
DOM4JUtil.java用於解析xml屬性檔案以獲得需要資料
PostgreSQL_Util.java分裝資料連線與資料庫操作
PageProperties.java為表格分頁屬性javaBean
PageProperties.java封裝分頁操作
Page.java為分頁主要操作
tablePage.jsp為效果顯示介面
用到的第三方jar包:
dom4j-1.6.1.jar用於xml檔案解析
postgresql-9.3-1101.jdbc4.jar用於JDBC串連postgreSQL資料庫
分頁效果如下:能通過點擊上頁下頁實現翻頁,輸入指定頁面跳轉(超出範圍跳轉到第1或最後頁)。具體實現請參見詳細代碼,我都貼上來了。小菜鳥一名,處於正在學習階段,有大神能指點下當然更好,希望不吝賜教!
二、具體代碼實現
1、config.xml資料庫連接資訊屬性檔案
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE postgres[ <!ELEMENT postgres (driver,url,username,pwd)> <!ELEMENT driver (#PCDATA)> <!ELEMENT url (#PCDATA)> <!ELEMENT username (#PCDATA)> <!ELEMENT pwd (#PCDATA)>]><postgres> <driver>org.postgresql.Driver</driver> <url>jdbc:postgresql://localhost:5432/java</url> <username>admin</username> <pwd>k42jc</pwd></postgres>
2、DOM4JUtil.java
package util;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 用於解析xml屬性檔案 * @author JohsonMuler * */public class DOM4JUtil { private static Element root=null; static{//靜態代碼塊 //建立解析對象 SAXReader sr=new SAXReader(); //擷取當前工程路徑// String url=System.getProperty("user.dir"); String url=DOM4JUtil.class.getResource("").getPath();// System.out.println(url); try { //通過檔案路徑擷取設定檔資訊 Document doc=sr.read(url+"config.xml"); //擷取根節點 root=doc.getRootElement(); } catch (DocumentException e) { e.printStackTrace(); } } public static String getPostgresData(String str){ //以根節點為基礎,擷取設定檔資料 Element e=root.element(str); String data=e.getText(); return data; } public static void main(String[] args) {// String url=DOM4JUtil.class.getResource("..").getPath();// System.out.println(System.getProperty("user.dir"));// System.out.println(url); String driver=getPostgresData("driver"); String url=getPostgresData("url"); System.out.println(driver); System.out.println(url); }}
3、PostgreSQL_Util.java
package util;import java.sql.PreparedStatement;import java.sql.Statement;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;public class PostgreSQL_Util { private static DOM4JUtil dom=new DOM4JUtil(); private static Connection c=null; private static ResultSet rs=null; private static String driver=dom.getPostgresData("driver"); private static String url=dom.getPostgresData("url"); private static String username=dom.getPostgresData("username"); private static String pwd=dom.getPostgresData("pwd"); public PostgreSQL_Util(){ try { Class.forName(driver); c=DriverManager.getConnection(url); } catch (ClassNotFoundException e) { System.out.println("未找到指定類:"+e.getMessage()); } catch (SQLException e) { System.out.println("擷取串連異常:"+e.getMessage()); } } /** * 資料查詢方法(Statement) * @param sql * @return * @throws SQLException */ public ResultSet executeQuery(String sql) throws SQLException{ Statement s=c.createStatement(); rs=s.executeQuery(sql); return rs; } /** * 重載方法(PreparedStatement) * @param sql * @param list * @return * @throws SQLException */ public ResultSet executeQuery(String sql,List<Object> list) throws SQLException{ PreparedStatement ps=c.prepareStatement(sql); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); System.out.println(i+1); ps.setObject(i+1, list.get(i)); } rs=ps.executeQuery(); c.close(); return rs; } /** * 資料更新方法(添加,刪除,更改)(Statement) * @param sql * @throws SQLException */ public int executeUpdate(String sql) throws SQLException{ Statement s=c.createStatement(); int i=s.executeUpdate(sql); c.close(); return i; } /** * 重載方法(PreparedStatement) * @param sql * @param list * @throws SQLException */ public int executeUpdate(String sql,List<Object> list) throws SQLException{ PreparedStatement ps=c.prepareStatement(sql); for(int i=0;i<list.size();i++){ ps.setObject(i+1, list.get(i)); } int i=ps.executeUpdate(); c.close(); return i; } /** * 單獨的擷取串連 * @return * @throws ClassNotFoundException * @throws SQLException */ public static Connection getConnection() throws ClassNotFoundException, SQLException{ Class.forName(driver); c=DriverManager.getConnection(url); return c; }}
4、PageProperties.java
package bean;import java.sql.ResultSet;public class PageProperties { private int currentPage;//當前頁號 private int totalPages;//總頁數 private int totalRecords;//總資料條數 private ResultSet rs;//動態結果集 public PageProperties() { super(); } public PageProperties(int currentPage, int totalPages, int totalRecords, ResultSet rs) { super(); this.currentPage = currentPage; this.totalPages = totalPages; this.totalRecords = totalRecords; this.rs = rs; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; }}
5、TablePage.java
package bean;import java.sql.ResultSet;public class PageProperties { private int currentPage;//當前頁號 private int totalPages;//總頁數 private int totalRecords;//總資料條數 private ResultSet rs;//動態結果集 public PageProperties() { super(); } public PageProperties(int currentPage, int totalPages, int totalRecords, ResultSet rs) { super(); this.currentPage = currentPage; this.totalPages = totalPages; this.totalRecords = totalRecords; this.rs = rs; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; }}
6、Page.java這是主要處理類,Servlet
package servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import util.PostgreSQL_Util;import bean.PageProperties;import bean.TablePage;public class Page extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); /** * 通過TablePage設定分頁屬性 * */ TablePage tb=new TablePage(); //擷取當前表格顯示的頁碼 int currentPage=tb.currentPage(tb.getStrPage(request, "page")); System.out.println(currentPage); //設定每頁顯示資料條數 tb.setPageRecord(10);//設定每頁顯示10條資料 /** * 通過xxSQL_Util設定JDBC串連及資料處理 */ PostgreSQL_Util postgres=new PostgreSQL_Util(); try { ResultSet rs_count=postgres.executeQuery("select count(*) as c from student"); rs_count.next(); //獲得總的資料條數 int totalRecords=rs_count.getInt("c"); //根據資料表的總資料條數擷取頁面顯示表格的總頁數 int totalPages=tb.getTotalPages(totalRecords); if(currentPage>totalPages){ currentPage=totalPages;//保證最後一頁不超出範圍 } //根據資料庫表資訊和當前頁面資訊獲得動態結果集 ResultSet rs=tb.getPageResultSet(postgres.executeQuery("select * from student"), currentPage); /** * 將資料加入javaBean */ PageProperties pp=new PageProperties(currentPage, totalPages, totalRecords, rs); /** * 將javaBean轉寄至前端 */ request.setAttribute("result", pp); request.getRequestDispatcher("tablePage.jsp").forward(request, response); } catch (SQLException e) { System.out.println("Class Page:"+e.getMessage());// e.printStackTrace(); } }}
7、tablePage.jsp前台顯示效果
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@page import="java.sql.ResultSet"%><%@page import="bean.PageProperties"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>簡單資料分頁</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <table> <tr> <td>姓名</td> <td>性別</td> <td>年齡</td> <td>分數</td> </tr> <% PageProperties pp=(PageProperties)request.getAttribute("result"); ResultSet rs=pp.getRs(); %> <% int i=1; while(rs.next()){ %> <tr> <td><%=rs.getObject(1) %></td> <td><%=rs.getObject(2) %></td> <td><%=rs.getObject(3) %></td> <td><%=rs.getObject(4) %></td> </tr> <% i++; if(i>10) break; } %> <br/> <span><%=pp.getTotalPages() %>頁</span> <span>共<%=pp.getTotalRecords() %>條資料</span> <span>本頁<%=i-1 %>條</span> <span>第<%=pp.getCurrentPage() %>頁</span> <p align="center"> <% if ( pp.getCurrentPage() > 1 ) { %><a href="<%=path %>/page?page=<%=pp.getCurrentPage() - 1%>"><<上一頁</a> <% } %> <% if ( pp.getCurrentPage() < pp.getTotalPages() ) { %><a href="<%=path %>/page?page=<%=pp.getCurrentPage() + 1%>">下一頁>></a> <% } %> <input type="text" name="input_text" id="input_text" size="1" /> <input type="button" name="skip" id="skip" value="跳轉" onclick="skip();"/> <script> function skip(){ var v=document.getElementById("input_text").value; location.href="page?page="+v; } </script> </p> </table> </body></html>
初步看,感覺後台代碼實在是繁瑣,但這是考慮到程式健壯性與可移植性,方便代碼重用。以後要用,根據自己的需要在屬性檔案(config.xml)中配置相關JDBC驅動,在jsp頁面通過request獲得後台Servlet(Page.jsp)的轉寄結果("result"),結合頁面屬性(PageProperties.java類)即可實現效果。
當然,這也是因為個人學習,傾向於多用點東西。
希望本文所述對大家jsp程式設計有所協助。