当前位置:网站首页>Paging in servlets and JSPS

Paging in servlets and JSPS

2022-07-01 06:57:00 allway2

Project description

  • This example shows how to use Servlet and JSP Write applications , The application uses paging to display the results .
  • This application uses a table Employee And display employee details to the user .
  • We use Eclipse IDE for Java EE Developers and Apache Tomcat To run the Servlet and JSP.
  • As best practice , We use Single case ( Used to establish database connection )、 Data access object (DAO) Transfer object (TO) and Model view controller (MVC) Pattern .

Usage environment

  • JDK 6 (Java SE 6)
  • oriented Java EE Developer's Eclipse Indigo IDE (3.7.1)
  • Apache Tomcat 6.x( To install Tomcat, Please refer to this page
  • MySQL 5.5( To install MySQL, Please refer to this page
  • MySQL The connector /J 5.1 JAR file
  • JSTL JAR file (jstl-1.2.jar)
  • Java EE 5 API(Servlet 2.5、JSP 2.1、JSTL 1.2、 Expression language (EL))
  • Java Database connection (JDBC) API
  • [ Optional ] To monitor and analyze browsers and Web Between servers HTTP header , You can use Firefox One of these add ons
    • real time HTTP header
    • HttpFox

Build development environment

If you are not familiar with using Tomcat and Eclipse Development Servlet, Before continuing with this example Read this page .

Program control flow

What is pagination ?

  • Getting millions of records from the database consumes almost all of the machine CPU Power and memory .
  • therefore , We split millions of records into small pieces , A limited number of records per page are displayed ( such as 20 or 30 strip ). The best example is Google search page , It allows users to navigate to the next page by page number and view a limited number of records per page .

How to implement paging ?

Paging logic can be implemented in many ways , Some are

Method 1 : greed method

  • Get all the records at once and display them to the user after caching the results . This is called the greedy method .
  • This can be done by writing back List<Object> Of DAO To achieve . Whenever users need results , You can retrieve a sublist from the cache list , Not when the user clicks “ next step ” Query the database when linking to get the next set of results .
  • The disadvantage of this method is , Because the data is cached , It becomes old . If your application changes the data in the result set , You may have to consider the accuracy of the results when choosing this solution .

Method 2: Non greedy method

  • Pass restrictions ResultSet The number of lines in , Get the record range every time the user wants to view .
  • What if you have more than millions of records ? Users may have to wait a long time to get results . ad locum , We limit the result set to only get the number of records that the user wants to view .

We use the second method to demonstrate paging .

stay MYSQL Create databases and tables in

This example uses a Employee surface , The table is described below .
“ staff ” surface

FIELDTYPEKEYEXTRA
emp_idintPrimary Keyauto_increment
emp_namevarchar(255)
salarydouble
dept_namevarchar(255)
  • Open Command Prompt (Windows) Or terminals (Linux) And type

    mysql -u [ Your username ] -p

    Then press enter and enter the password .

  • If you are using Windows, You can also use it MySQL Command line client , This client will be available in all program menus .
  • To create a new database , Please refer to this page . In this example , The database name is “ exampledb ”.
  • After creating the database , Enter the command “use <database_name>;”
  • To create a new table , Please refer to this page . In this case , Table name is ' staff '
  • Insert some records into the table . Please refer to this page To use the MySQL Insert row .

Create dynamic WEB project

  • open Eclipse IDE
  • In order to write Servlet and JSP, We need to create a new Dynamic Web project . Create this project and name it “ JSPPagination ”.

download MYSQL The connector

  • Connectors can be from :http ://dev.mysql.com/downloads/connector/j/ download .
  • This tutorial USES 5.1 edition . Unzip the connector to your computer, including MySQL Connector J JAR Safe location for .
  • Copy MySQL Connector J JAR And paste it into the “lib” In the folder .

download JSTL JAR file

  • JSTL JAR The file can be downloaded from the following website :http: //download.java.net/maven/1/jstl/jars/
  • This tutorial USES jstl-1.2.jar file .
  • Copy JAR File and paste it into the project “lib” In the folder .

Write the transfer object class

  • stay src In the folder , Create a New package And named it ' com.theopentutorials.to '. Create a new class in this package , As shown below .
  • Transfer Object Encapsulates business data . In order to realize this mode , We write a class with attributes that define table attributes .

Employee.java class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
packagecom.theopentutorials.to;
 
publicclassEmployee {
    privateintemployeeId;
    privateString employeeName;
    privatedoublesalary;
    privateString deptName;
     
    publicintgetEmployeeId() {
        returnemployeeId;
    }
    publicvoidsetEmployeeId(intemployeeId) {
        this.employeeId = employeeId;
    }
    publicString getEmployeeName() {
        returnemployeeName;
    }
    publicvoidsetEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    publicdoublegetSalary() {
        returnsalary;
    }
    publicvoidsetSalary(doublesalary) {
        this.salary = salary;
    }
    publicString getDeptName() {
        returndeptName;
    }
    publicvoidsetDeptName(String deptName) {
        this.deptName = deptName;
    }
}

Write the connection factory class

Writing DAO Before class , Let's write a ConnectionFactory class , It has the database connection configuration statement and the method of connecting to the database . This class uses singleton mode .

stay src In the folder Create a new package and name it com.theopentutorials.db And copy the following code .

ConnectionFactory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
packagecom.theopentutorials.db;
 
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.SQLException;
 
publicclassConnectionFactory {
    //static reference to itself
    privatestaticConnectionFactory instance =
                newConnectionFactory();
    String url = "jdbc:mysql://localhost/exampledb";
    String user = "<YOUR_DATABASE_USERNAME>";
    String password = "<YOUR_DATABASE_PASSWORD>";
    String driverClass = "com.mysql.jdbc.Driver";
     
    //private constructor
    privateConnectionFactory() {
        try{
            Class.forName(driverClass);
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
     
    publicstaticConnectionFactory getInstance()   {
        returninstance;
    }
     
    publicConnection getConnection() throwsSQLException,
    ClassNotFoundException {
        Connection connection =
            DriverManager.getConnection(url, user, password);
        returnconnection;
    }  
}

Fill in the user name and password of the database , And in url Enter your database name in the string .

To write DAO class

This class uses data access objects that encapsulate access to data sources (DAO) Pattern .
EmployeeDAO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
packagecom.theopentutorials.dao;
 
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
importjava.util.ArrayList;
importjava.util.List;
importcom.theopentutorials.db.ConnectionFactory;
importcom.theopentutorials.to.Employee;
 
publicclassEmployeeDAO {
    Connection connection;
    Statement stmt;
    privateintnoOfRecords;
         
    publicEmployeeDAO() { }
     
    privatestaticConnection getConnection()
            throwsSQLException,
                ClassNotFoundException
    {
        Connection con = ConnectionFactory.
                getInstance().getConnection();
        returncon;
    }
     
    publicList<Employee> viewAllEmployees(
                intoffset,
                intnoOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit "
                 + offset + ", "+ noOfRecords;
        List<Employee> list = newArrayList<Employee>();
        Employee employee = null;
        try{
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next()) {
                employee = newEmployee();
                employee.setEmployeeId(rs.getInt("emp_id"));
                employee.setEmployeeName(rs.getString("emp_name"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setDeptName(rs.getString("dept_name"));
                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();
            }
        }
        returnlist;
    }
 
    publicintgetNoOfRecords() {
        returnnoOfRecords;
    }
}

One SELECT The statement may contain a LIMIT Clause To limit the number of rows returned by the server to the client . This LIMIT Clause has two arguments ; The first parameter specifies the offset of the first line to return , The second parameter specifies the maximum number of rows to return .

In some cases , Hope to know if there is LIMIT How many lines will this statement return , But there is no need to run the statement again . To get the number of rows , Please be there. SELECT The statement contains SQL_CALC_FOUND_ROWS Options , And then call FOUND_ROWS()

To write SERVLET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
packagecom.theopentutorials.servlets;
 
importjava.io.IOException;
importjava.util.List;
importjavax.servlet.RequestDispatcher;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.theopentutorials.dao.EmployeeDAO;
importcom.theopentutorials.to.Employee;
 
/**
 * Servlet implementation class EmployeeServlet
 */
publicclassEmployeeServlet extendsHttpServlet {
    privatestaticfinallongserialVersionUID = 1L;
        
    publicEmployeeServlet() {
            super();
    }
 
    publicvoiddoGet(HttpServletRequest request,
            HttpServletResponse response)
            throwsServletException, IOException {
        intpage = 1;
        intrecordsPerPage = 5;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
        EmployeeDAO dao = newEmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
                                 recordsPerPage);
        intnoOfRecords = dao.getNoOfRecords();
        intnoOfPages = (int) Math.ceil(noOfRecords * 1.0/ recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("displayEmployee.jsp");
        view.forward(request, response);
    }
}
  • stay Servlet in , We get... First 'page' Parameter and store it in 'page' variable . We want to show five... Per page (5) Bar record , We pass it as a parameter to viewAllEmployees(offset, 5). We store three properties in the request scope and forward the request to JSP page (displayEmployee.jsp);
    • 'list' List of employees available in the variable
    • “noOfPages” The total number of pages available in the variable
    • The current page is in “ page ” Available in variables

To write WEB.XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xmlversion="1.0"encoding="UTF-8"?>
    /web-app_2_5.xsd" id="WebApp_ID"version="2.5">
  <display-name>JSPPagination</display-name>
  <servlet>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>com.theopentutorials.servlets.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/employee.do</url-pattern>
  </servlet-mapping>
</web-app>

To write DISPLAYEMPLOYEE.JSP

this JSP Page using JSP Standard tag library (JSTL) And expression languages (EL). It retrieves properties from the request scope and displays the results . To use JSTL library , You must be in JSP The page contains <taglib> Instructions .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<%@ page language="java"contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="Oracle Java Technologies | Oracle"prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Employees</title>
</head>
<body>
    <table border="1"cellpadding="5"cellspacing="5">
        <tr>
            <th>Emp ID</th>
            <th>Emp Name</th>
            <th>Salary</th>
            <th>Dept Name</th>
        </tr>
 
        <c:forEach var="employee"items="${employeeList}">
            <tr>
                <td>${employee.employeeId}</td>
                <td>${employee.employeeName}</td>
                <td>${employee.salary}</td>
                <td>${employee.deptName}</td>
            </tr>
        </c:forEach>
    </table>
 
    <%--For displaying Previous link except forthe 1st page --%>
    <c:iftest="${currentPage != 1}">
        <td><a href="employee.do?page=${currentPage - 1}">Previous</a></td>
    </c:if>
 
    <%--For displaying Page numbers.
    The when condition does not display a link forthe current page--%>
    <table border="1"cellpadding="5"cellspacing="5">
        <tr>
            <c:forEach begin="1"end="${noOfPages}"var="i">
                <c:choose>
                    <c:when test="${currentPage eq i}">
                        <td>${i}</td>
                    </c:when>
                    <c:otherwise>
                        <td><a href="employee.do?page=${i}">${i}</a></td>
                    </c:otherwise>
                </c:choose>
            </c:forEach>
        </tr>
    </table>
     
    <%--For displaying Next link --%>
    <c:iftest="${currentPage lt noOfPages}">
        <td><a href="employee.do?page=${currentPage + 1}">Next</a></td>
    </c:if>
 
</body>
</html>

first “ surface ” The tab displays a list of employees and their details . the second “ surface ” The label shows the page number .

Folder structure

The complete folder structure of this example is shown below .

 

Output

stay Eclipse Use in Ctrl + F11 To run the Servlet. request Servlet Of URL yes
http://localhost:8080/JSPPagination/employee.do

原网站

版权声明
本文为[allway2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010645321875.html