📜  Servlet – 分页示例

📅  最后修改于: 2022-05-13 01:55:26.808000             🧑  作者: Mango

Servlet – 分页示例

分页是一系列相互连接并具有相似内容的页面。分页是一种将多条记录列表拆分为子项的技术。例如,您在 Google 上使用关键字搜索并收到数以万计的结果。重要的是要注意,即使页面部分的内容被分成不同的页面,我们仍将其定义为分页。

Java中的分页

为了将大量记录分成多个部分,我们使用分页。它允许用户仅显示部分记录。在单个页面上加载所有记录可能需要一些时间,因此始终建议创建分页。在Java中,我们可以轻松开发分页示例。在这个分页示例中,我们使用 MySQL 数据库来获取记录。

例子

步骤 1 :在 Mysql 中创建一个表

create table employee(empid int(11),empname varchar(20),empsalary int(11),empdept varchar(20));

第 2 步:创建一个 JavaBean 类,用于为数据库设置值并从数据库中获取值。

Java
public class Employee {
    int employeeId;
    String employeeName;
    int salary;
    String deptName;
  
    public String getDeptName() { return deptName; }
  
    public void setDeptName(String deptName)
    {
        this.deptName = deptName;
    }
  
    public int getEmployeeId() { return employeeId; }
  
    public void setEmployeeId(int employeeId)
    {
        this.employeeId = employeeId;
    }
  
    public String getEmployeeName() { return employeeName; }
  
    public void setEmployeeName(String employeeName)
    {
        this.employeeName = employeeName;
    }
  
    public int getSalary() { return salary; }
  
    public void setSalary(int salary)
    {
        this.salary = salary;
    }
}


Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
  
public class ConnectionFactory {
  
    // static reference to itself
    private static ConnectionFactory instance = new ConnectionFactory();
  
    String url = "jdbc:mysql://localhost:3306/ashok";
    String user = "root";
    String password = "";
    String driverClass = "com.mysql.jdbc.Driver";
  
    // private constructor
    private ConnectionFactory()
    {
        try {
            Class.forName(driverClass);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  
    public static ConnectionFactory getInstance()
    {
        return instance;
    }
  
    public Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
}


Java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
  
public class EmployeeDAO {
  
    Connection connection;
    Statement stmt;
    
    private int noOfRecords;
    public EmployeeDAO() {}
  
    private static Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection con = ConnectionFactory.getInstance().getConnection();
        return con;
    }
  
    public List viewAllEmployees(int offset, int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit " + offset + ", " + noOfRecords;
        List list = new ArrayList();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt(1));
                employee.setEmployeeName(rs.getString(2));
                employee.setSalary(rs.getInt(3));
                employee.setDeptName(rs.getString(4));
                list.add(employee);
            }
  
            rs.close();
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
  
            if (rs.next())
               this.noOfRecords = rs.getInt(1);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    public int getNoOfRecords() { return noOfRecords; }
}


Java
import a1.Employee;
import a1.EmployeeDAO;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
public class EmployeeServlet extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
    public EmployeeServlet() { super(); }
  
    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
        int page = 1;
        int recordsPerPage = 5;
        if (request.getParameter("page") != null)
            page = Integer.parseInt(
                request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List list = dao.viewAllEmployees(
            (page - 1) * recordsPerPage,
            recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int)Math.ceil(noOfRecords * 1.0
                                       / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view
            = request.getRequestDispatcher("display.jsp");
        view.forward(request, response);
    }
}


XML


  
   
       EmployeeServlet
       a2.EmployeeServlet
   
  
   
       EmployeeServlet
       /employee.do
   
  
   
       30
   
  


HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  
  pageEncoding="ISO-8859-1"%>
  
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  

  

  


Employees

  

  
      
          
          
          
          
      
  
      
          
              
              
              
              
          
      
  
  
Emp IDEmp NameSalaryDept Name
${employee.employeeId}${employee.employeeName}${employee.salary}${employee.deptName}
     <%--For displaying Previous link except for the 1st page --%>          Previous         <%--For displaying Page numbers. The when condition does not display               a link for the current page--%>                                                                                                                                                                                                     
${i}${i}
     <%--For displaying Next link --%>             Next         


第 3 步:为从数据库获取连接创建一个工厂类。

Java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
  
public class ConnectionFactory {
  
    // static reference to itself
    private static ConnectionFactory instance = new ConnectionFactory();
  
    String url = "jdbc:mysql://localhost:3306/ashok";
    String user = "root";
    String password = "";
    String driverClass = "com.mysql.jdbc.Driver";
  
    // private constructor
    private ConnectionFactory()
    {
        try {
            Class.forName(driverClass);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  
    public static ConnectionFactory getInstance()
    {
        return instance;
    }
  
    public Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
}

第 4 步:创建一个 Dao 类,用于创建工厂类 Object 并调用该方法。并创建一个查询并将其设置为 JavaBean 对象并添加到 ArrayList 对象。

Java

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
  
public class EmployeeDAO {
  
    Connection connection;
    Statement stmt;
    
    private int noOfRecords;
    public EmployeeDAO() {}
  
    private static Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection con = ConnectionFactory.getInstance().getConnection();
        return con;
    }
  
    public List viewAllEmployees(int offset, int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit " + offset + ", " + noOfRecords;
        List list = new ArrayList();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt(1));
                employee.setEmployeeName(rs.getString(2));
                employee.setSalary(rs.getInt(3));
                employee.setDeptName(rs.getString(4));
                list.add(employee);
            }
  
            rs.close();
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
  
            if (rs.next())
               this.noOfRecords = rs.getInt(1);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    public int getNoOfRecords() { return noOfRecords; }
}

第五步:创建一个Servlet类并创建一个DAO类Object并调用该方法并转发到display.jsp页面

Java

import a1.Employee;
import a1.EmployeeDAO;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
public class EmployeeServlet extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
    public EmployeeServlet() { super(); }
  
    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
        int page = 1;
        int recordsPerPage = 5;
        if (request.getParameter("page") != null)
            page = Integer.parseInt(
                request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List list = dao.viewAllEmployees(
            (page - 1) * recordsPerPage,
            recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int)Math.ceil(noOfRecords * 1.0
                                       / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view
            = request.getRequestDispatcher("display.jsp");
        view.forward(request, response);
    }
}

第 6 步:配置 web.xml 文件

XML



  
   
       EmployeeServlet
       a2.EmployeeServlet
   
  
   
       EmployeeServlet
       /employee.do
   
  
   
       30
   
  

第 7 步:创建display.jsp文件以显示 5 到 5 条记录的记录

HTML

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  
  pageEncoding="ISO-8859-1"%>
  
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  

  

  


Employees

  

  
      
          
          
          
          
      
  
      
          
              
              
              
              
          
      
  
  
Emp IDEmp NameSalaryDept Name
${employee.employeeId}${employee.employeeName}${employee.salary}${employee.deptName}
     <%--For displaying Previous link except for the 1st page --%>          Previous         <%--For displaying Page numbers. The when condition does not display               a link for the current page--%>                                                                                                                                                                                                     
${i}${i}
     <%--For displaying Next link --%>             Next         

输出

Emp IdEmp NameSalaryDp Name
101Raj5000Bca
102Karan7000mca
103Amit4000bcom
104Manisha8000Mba
105Sakshi3000BA

从数据库中获取数百万条记录几乎消耗了机器的所有 CPU 功率和内存。因此,我们将数百万条记录分成小块,每页显示有限数量的记录(比如 5 或 10 条)。