<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java Servlet 分頁 > 原文: [http://zetcode.com/articles/javaservletpagination/](http://zetcode.com/articles/javaservletpagination/) Java servlet 分頁教程顯示了如何使用 Java servlet 進行分頁。 在示例中,Bootstrap 用于 UI。 ## 分頁 分頁是將內容分為幾頁的過程。 用戶具有用于通過特定頁面鏈接訪問這些頁面的導航界面。 導航通常包括上一個/下一個和第一個/最后一個鏈接。 當數據庫中有大量數據或一頁中顯示許多項時,將使用分頁。 ## Java Servlet Servlet 是 Java 類,可響應特定類型的網絡請求-最常見的是 HTTP 請求。 Java servlet 用于創建 Web 應用。 它們在 servlet 容器(例如 Tomcat 或 Jetty)中運行。 現代 Java Web 開發使用在 servlet 之上構建的框架。 ## Bootstrap Bootstrap 是 Twitter 的一個 UI 庫,用于創建響應式,移動優先的 Web 應用。 ## Java Servlet 分頁示例 在以下應用中,我們從 MySQL 數據庫加載數據并將其顯示在表中。 有一個導航系統可以遍歷數據庫表中的所有數據。 在將數據顯示在表中之前,用戶可以選擇表將顯示多少行。 除了從數據庫表中獲取數據之外,我們還需要知道數據庫表中所有行的數量,每頁的記錄數以及要在導航中顯示的頁面數。 SQL 語句可以計算出數據庫中所有行的數量。 用戶以 HTML 格式選擇每頁的記錄數。 最后,從其他兩個值計算分頁中的頁數。 `countries_mysql.sql` ```java CREATE TABLE Countries(ID BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(100), Population INT); INSERT INTO Countries(Name, Population) VALUES('China', 1382050000); INSERT INTO Countries(Name, Population) VALUES('India', 1313210000); INSERT INTO Countries(Name, Population) VALUES('USA', 324666000); INSERT INTO Countries(Name, Population) VALUES('Indonesia', 260581000); INSERT INTO Countries(Name, Population) VALUES('Brazil', 207221000); INSERT INTO Countries(Name, Population) VALUES('Pakistan', 196626000); INSERT INTO Countries(Name, Population) VALUES('Nigeria', 186988000); INSERT INTO Countries(Name, Population) VALUES('Bangladesh', 162099000); INSERT INTO Countries(Name, Population) VALUES('Nigeria', 186988000); INSERT INTO Countries(Name, Population) VALUES('Russia', 146838000); INSERT INTO Countries(Name, Population) VALUES('Japan', 126830000); INSERT INTO Countries(Name, Population) VALUES('Mexico', 122273000); INSERT INTO Countries(Name, Population) VALUES('Philippines', 103738000); INSERT INTO Countries(Name, Population) VALUES('Ethiopia', 101853000); INSERT INTO Countries(Name, Population) VALUES('Vietnam', 92700000); INSERT INTO Countries(Name, Population) VALUES('Egypt', 92641000); INSERT INTO Countries(Name, Population) VALUES('Germany', 82800000); INSERT INTO Countries(Name, Population) VALUES('the Congo', 82243000); INSERT INTO Countries(Name, Population) VALUES('Iran', 82800000); INSERT INTO Countries(Name, Population) VALUES('Turkey', 79814000); INSERT INTO Countries(Name, Population) VALUES('Thailand', 68147000); INSERT INTO Countries(Name, Population) VALUES('France', 66984000); INSERT INTO Countries(Name, Population) VALUES('United Kingdom', 60589000); INSERT INTO Countries(Name, Population) VALUES('South Africa', 55908000); INSERT INTO Countries(Name, Population) VALUES('Myanmar', 51446000); INSERT INTO Countries(Name, Population) VALUES('South Korea', 68147000); INSERT INTO Countries(Name, Population) VALUES('Colombia', 49129000); INSERT INTO Countries(Name, Population) VALUES('Kenya', 47251000); INSERT INTO Countries(Name, Population) VALUES('Spain', 46812000); INSERT INTO Countries(Name, Population) VALUES('Argentina', 43850000); INSERT INTO Countries(Name, Population) VALUES('Ukraine', 42603000); INSERT INTO Countries(Name, Population) VALUES('Sudan', 41176000); INSERT INTO Countries(Name, Population) VALUES('Algeria', 40400000); INSERT INTO Countries(Name, Population) VALUES('Poland', 38439000); ``` 該 SQL 腳本在 MySQL 中創建`Countries`表。 ```java $ tree . ├── nb-configuration.xml ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── bean │ │ │ └── Country.java │ │ ├── service │ │ │ ├── CountryService.java │ │ │ └── ICountryService.java │ │ └── web │ │ └── ReadCountries.java │ ├── resources │ └── webapp │ ├── index.html │ ├── listCountries.jsp │ ├── META-INF │ │ └── context.xml │ └── WEB-INF └── test └── java ``` 這是項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>JavaServletPagination</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>JavaServletPagination</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> ``` 這是 Maven POM 文件。 `javax.servlet-api`工件用于 servlet。 `spring-jdbc`依賴項用于`JdbcTemplate`庫,該庫簡化了 Java 中的數據庫編程。 `mysql-connector-java`是 Java 語言的 MySQL 驅動程序。 `jstl`依賴項為 JSP 頁面提供了一些附加功能。 `maven-war-plugin`負責收集 Web 應用的所有工件依賴項,類和資源,并將它們打包到 Web 應用存檔(WAR)中。 `context.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <Context path="/JavaServletPagination"/> ``` 在 Tomcat `context.xml`文件中,我們定義了上下文路徑。 它是 Web 應用的名稱。 `Country.java` ```java package com.zetcode.bean; public class Country { private String name; private int population; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } } ``` `Country` bean 從`Countries`數據庫表中保留一行。 `ReadCountries.java` ```java package com.zetcode.web; import com.zetcode.bean.Country; import com.zetcode.service.CountryService; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "ReadCountries", urlPatterns = {"/ReadCountries"}) public class ReadCountries extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int currentPage = Integer.valueOf(request.getParameter("currentPage")); int recordsPerPage = Integer.valueOf(request.getParameter("recordsPerPage")); CountryService countryService = new CountryService(); List<Country> countries = countryService.findCountries(currentPage, recordsPerPage); request.setAttribute("countries", countries); int rows = countryService.getNumberOfRows(); int nOfPages = rows / recordsPerPage; if (nOfPages % recordsPerPage > 0) { nOfPages++; } request.setAttribute("noOfPages", nOfPages); request.setAttribute("currentPage", currentPage); request.setAttribute("recordsPerPage", recordsPerPage); RequestDispatcher dispatcher = request.getRequestDispatcher("listCountries.jsp"); dispatcher.forward(request, response); } } ``` `ReadCountries` Servlet 確定將從請求屬性中檢索多少數據,并從數據庫表中讀取指定的行數。 ```java @WebServlet(name = "ReadCountries", urlPatterns = {"/ReadCountries"}) ``` Java 類用`@WebServlet`注解修飾。 它映射到`ReadCountries` URL 模式。 ```java response.setContentType("text/html;charset=UTF-8"); ``` Servlet 將以 HTML 輸出數據,并且數據的編碼設置為 UTF-8。 ```java int currentPage = Integer.valueOf(request.getParameter("currentPage")); int recordsPerPage = Integer.valueOf(request.getParameter("recordsPerPage")); ``` 從請求中我們得到兩個重要的值:當前頁和每頁的記錄數。 ```java CountryService countryService = new CountryService(); List<Country> countries = countryService.findCountries(currentPage, recordsPerPage); request.setAttribute("countries", countries); ``` `CountryService`是用于連接到數據庫并讀取數據的服務類。 檢索國家列表并將其設置為請求的屬性。 稍后將由目標 JSP 頁面使用。 ```java int rows = countryService.getNumberOfRows(); int nOfPages = rows / recordsPerPage; if (nOfPages % recordsPerPage > 0) { nOfPages++; } ``` 我們使用`getNumberOfRows()`服務方法從數據庫表中獲取所有行的數目。 我們計算導航中的頁面數。 ```java request.setAttribute("noOfPages", nOfPages); request.setAttribute("currentPage", currentPage); request.setAttribute("recordsPerPage", recordsPerPage); ``` 頁數,當前頁和每頁的記錄數是我們建立分頁所需的值。 ```java RequestDispatcher dispatcher = request.getRequestDispatcher("listCountries.jsp"); dispatcher.forward(request, response); ``` 處理被轉發到`listCountries.jsp`頁面。 `ICountryService.java` ```java package com.zetcode.service; import com.zetcode.bean.Country; import java.util.List; public interface ICountryService { public List<Country> findCountries(int currentPage, int numOfRecords); public int getNumberOfRows(); } ``` `ICountryService`包含兩種簽約方法:`findCountries()`和`getNumberOfRows()`。 `CountryService.java` ```java package com.zetcode.service; import com.zetcode.bean.Country; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SimpleDriverDataSource; public class CountryService implements ICountryService { @Override public List<Country> findCountries(int currentPage, int recordsPerPage) { List<Country> countries = null; int start = currentPage * recordsPerPage - recordsPerPage; try { String sql = "SELECT * FROM Countries LIMIT ?, ?"; SimpleDriverDataSource ds = new SimpleDriverDataSource(); ds.setDriver(new com.mysql.jdbc.Driver()); ds.setUrl("jdbc:mysql://localhost:3306/testdb"); ds.setUsername("testuser"); ds.setPassword("test623"); JdbcTemplate jtm = new JdbcTemplate(ds); countries = jtm.query(sql, new Object[] {start, recordsPerPage}, new BeanPropertyRowMapper(Country.class)); } catch (SQLException ex) { Logger.getLogger(CountryService.class.getName()).log(Level.SEVERE, null, ex); } return countries; } @Override public int getNumberOfRows() { int numOfRows = 0; try { String sql = "SELECT COUNT(Id) FROM Countries"; SimpleDriverDataSource ds = new SimpleDriverDataSource(); ds.setDriver(new com.mysql.jdbc.Driver()); ds.setUrl("jdbc:mysql://localhost:3306/testdb"); ds.setUsername("testuser"); ds.setPassword("test623"); JdbcTemplate jtm = new JdbcTemplate(ds); numOfRows = jtm.queryForObject(sql, Integer.class); } catch (SQLException ex) { Logger.getLogger(CountryService.class.getName()).log(Level.SEVERE, null, ex); } return numOfRows; } } ``` `CountryService`包含兩種合同方法的實現。 ```java String sql = "SELECT * FROM Countries LIMIT ?, ?"; ``` SQL `LIMIT`子句用于獲取當前頁面的行數。 ```java JdbcTemplate jtm = new JdbcTemplate(ds); countries = jtm.query(sql, new Object[] {start, recordsPerPage}, new BeanPropertyRowMapper(Country.class)); ``` `JdbcTemplate`用于執行 SQL 語句。 在`BeanPropertyRowMapper`的幫助下,行自動映射到`Country` bean。 ```java String sql = "SELECT COUNT(Id) FROM Countries"; ``` 通過此 SQL 語句,我們從數據庫表中獲取行數。 `index.html` ```java <!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"> </head> <body class="m-3"> <h1>Show countries</h1> <form action="ReadCountries"> <input type="hidden" name="currentPage" value="1"> <div class="form-group col-md-4"> <label for="records">Select records per page:</label> <select class="form-control" id="records" name="recordsPerPage"> <option value="5">5</option> <option value="10" selected>10</option> <option value="15">15</option> </select> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" ></script> </body> </html> ``` 這是主頁。 它包含一個 HTML 表單,用于通過`select`標簽選擇每頁的記錄數。 該表單使用 Bootstrap 庫中的樣式類。 提交表單后,處理將發送到`ReadCountries` Servlet。 ```java <input type="hidden" name="currentPage" value="1"> ``` 該表單包含一個隱藏的`input`標記,該標記將`currentPage`參數設置為 1。 ```java <select class="form-control" id="records" name="recordsPerPage"> <option value="5">5</option> <option value="10" selected>10</option> <option value="15">15</option> </select> ``` `select`標簽允許每頁選擇 5、10 或 15 條記錄。 ```java <button type="submit" class="btn btn-primary">Submit</button> ``` 提交按鈕執行表單。 `listCountries.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Countries</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"> </head> <body class="m-3"> <div class="row col-md-6"> <table class="table table-striped table-bordered table-sm"> <tr> <th>Name</th> <th>Population</th> </tr> <c:forEach items="${countries}" var="country"> <tr> <td>${country.getName()}</td> <td>${country.getPopulation()}</td> </tr> </c:forEach> </table> </div> <nav aria-label="Navigation for countries"> <ul class="pagination"> <c:if test="${currentPage != 1}"> <li class="page-item"><a class="page-link" href="ReadCountries?recordsPerPage=${recordsPerPage}&currentPage=${currentPage-1}">Previous</a> </li> </c:if> <c:forEach begin="1" end="${noOfPages}" var="i"> <c:choose> <c:when test="${currentPage eq i}"> <li class="page-item active"><a class="page-link"> ${i} <span class="sr-only">(current)</span></a> </li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="ReadCountries?recordsPerPage=${recordsPerPage}&currentPage=${i}">${i}</a> </li> </c:otherwise> </c:choose> </c:forEach> <c:if test="${currentPage lt noOfPages}"> <li class="page-item"><a class="page-link" href="ReadCountries?recordsPerPage=${recordsPerPage}&currentPage=${currentPage+1}">Next</a> </li> </c:if> </ul> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script> </body> </html> ``` `listCountries.jsp`在表格和分頁系統中顯示數據。 Bootstrap 用于使 UI 響應并看起來不錯。 ```java <table class="table table-striped table-bordered table-sm"> ``` `table`,`table-striped`,`table-bordered`和`table-sm`都是 Bootstrap 類。 ```java <c:forEach items="${countries}" var="country"> <tr> <td>${country.getName()}</td> <td>${country.getPopulation()}</td> </tr> </c:forEach> ``` 使用 JSTL 的`forEach`標簽,我們可以顯示當前頁面的所有數據。 ```java <c:if test="${currentPage != 1}"> <li class="page-item"><a class="page-link" href="ReadCountries?recordsPerPage=${recordsPerPage}&currentPage=${currentPage-1}">Previous</a> </li> </c:if> ``` 使用`c:if`標簽,我們僅在存在前一個鏈接時顯示它。 在鏈接中,我們將`recordsPerPage`和`currentPage`值傳遞給請求對象。 ```java <c:forEach begin="1" end="${noOfPages}" var="i"> <c:choose> <c:when test="${currentPage eq i}"> <li class="page-item active"><a class="page-link"> ${i} <span class="sr-only">(current)</span></a> </li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="ReadCountries?recordsPerPage=${recordsPerPage}&currentPage=${i}">${i}</a> </li> </c:otherwise> </c:choose> </c:forEach> ``` 使用`forEach`標簽,我們顯示所有頁面鏈接。 ![Java Servlet Pagination](https://img.kancloud.cn/e9/ba/e9ba579855713d34d9fd9a5225132e21_663x522.jpg) 圖:Java Servlet 分頁 該示例顯示了一個裝有數據和分頁系統的表。 當前選擇的頁面突出顯示。 在本教程中,我們展示了如何使用 Java Servlet 在 Web 應用中創建分頁系統。 您可能也對以下相關教程感興趣: [Java Servlet 上傳文件](/articles/javaservletuploadfile/), [Java Log4j 教程](/java/log4j/), [Java Servlet RESTful 客戶端](/articles/javaservletrestclient/), [Java `RequestDispatcher`](/java/requestdispatcher/) ,[從 Java servlet 提供純文本](/articles/javaservlettext/) , [Java servlet 圖像教程](/articles/javaservletimage/)或 [Java 教程](/lang/java/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看