本文实例讲述了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="https://www.atool.online/article/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="https://www.atool.online/article/<%=path %>/page?page=<%=pp.getCurrentPage() - 1%>"><<上一页</a>
   <%
    }
   %>
   <%
    if ( pp.getCurrentPage() < pp.getTotalPages() )
    {
   %><a href="https://www.atool.online/article/<%=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="https://www.atool.online/article/page?page="+v;
    }
   </script>
  </p>
 </table>
 </body>
</html>

初步看,感觉后台代码实在是繁琐,但这是考虑到程序健壮性与可移植性,方便代码重用。以后要用,根据自己的需要在属性文件(config.xml)中配置相关JDBC驱动,在jsp页面通过request获得后台Servlet(Page.jsp)的转发结果("result"),结合页面属性(PageProperties.java类)即可实现效果。

当然,这也是因为个人学习,倾向于多用点东西。

希望本文所述对大家jsp程序设计有所帮助。

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部