Home > php教程 > PHP开发 > Complete example of data paging method implemented by jsp+servlet+javabean

Complete example of data paging method implemented by jsp+servlet+javabean

高洛峰
Release: 2016-12-29 15:25:48
Original
1802 people have browsed it

The example of this article describes the jsp+servlet+javabean implementation of data paging method. I share it with you for your reference. The details are as follows:

Here we record the learning process with the mentality of walking and remembering. Learn quickly and forget quickly, for fear of forgetting, for future use.
Some of the codes used were found online and modified by myself, adding my own understanding. I don’t know if it’s original or not, I’m just recording my own learning.

Usage related: PostgreSQL database, dom4j, JSP, Servlet

First, the project layout, a global view to facilitate readers and themselves to view and use

Complete example of data paging method implemented by jsp+servlet+javabean

The idea is:

Use the config.xml file to record configuration information to facilitate database changes, transplantation and reuse.
DOM4JUtil.java is used to parse xml attribute files to obtain the required data
PostgreSQL_Util.java packages data connections and database operations
PageProperties.java is the table paging attribute javaBean
PageProperties.java encapsulates paging operations
Page.java is the main operation of paging
tablePage.jsp is the effect display interface

The third-party jar package used:

dom4j-1.6.1.jar is used for xml files Analysis
postgresql-9.3-1101.jdbc4.jar is used for JDBC connection to postgreSQL database

The paging effect is as follows: you can turn pages by clicking on the previous page and next page, and enter the specified page to jump (jump out of range) to the 1st or last page). For the specific implementation, please see the detailed code, which I have posted. I am a newbie and am still in the learning stage. It would be better if a master can give me some guidance. I hope you will give me some advice!

Complete example of data paging method implemented by jsp+servlet+javabean

2. Specific code implementation

1. config.xml database connection information attribute file

<?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>
Copy after login

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);
 }
}
Copy after login

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;
 }
}
Copy after login

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;
 }
}
Copy after login

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;
 }
}
Copy after login

6, Page.java This is the main processing Class, 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();
  }
 }
}
Copy after login

7, tablePage.jsp front-end display effect

<%@ 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>
Copy after login

At first glance, the background code seems to be really cumbersome, but this is to take into account the robustness and portability of the program, and to facilitate the code Reuse. For future use, configure the relevant JDBC driver in the properties file (config.xml) according to your own needs, obtain the forwarding result ("result") of the background Servlet (Page.jsp) through request on the jsp page, and combine it with the page properties (PageProperties. java class) can achieve the effect.

Of course, this is also because of personal study and tendency to use more things.

I hope this article will be helpful to everyone in jsp programming.

For more complete examples of jsp+servlet+javabean implementation of data paging method, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template