本文實例講述了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程序設計有所幫助。