<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國際加速解決方案。 廣告
                # servlet 從 WAR 內讀取 CSV 文件 > 原文: [http://zetcode.com/articles/warcsv/](http://zetcode.com/articles/warcsv/) 在本教程中,我們從`WEB-INF`目錄中的 CSV 文件讀取數據。 我們使用 servlet,JSP 文件和 JSTL 庫。 Web 應用已部署在 Jetty 上。 OpenCSV 庫用于讀取 CSV 數據。 ## CSV CSV(逗號分隔值)格式是在電子表格和數據庫中使用的非常流行的導入和導出格式。 在以下 Web 應用中,我們從 WAR 文件中的 CSV 文件讀取數據,并將數據顯示在網頁中。 標記人口超過一億的國家。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───bean │ │ │ Country.java │ │ ├───service │ │ │ CountryService.java │ │ └───web │ │ ReadCountries.java │ ├───resources │ │ countries.csv │ └───webapp │ index.jsp │ listCountries.jsp │ showError.jsp └───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>readcsvfromwar</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>12</maven.compiler.source> <maven.compiler.target>12</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.6</version> </dependency> <dependency> <groupId>jstl</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>3.2.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.14.v20181114</version> </plugin> </plugins> </build> </project> ``` 該項目使用以下依賴項:`avax.servlet-api`,`opencsv`和`jstl`。 `resources/countries.csv` ```java Name, Population Slovakia,5429000 Norway,5271000 Croatia,4225000 Russia,143439000 Mexico,122273000 Vietnam,95261000 Sweden,9967000 Iceland,337600 Israel,8622000 Hungary,9830000 Germany,82175700 Japan,126650000 ``` 這是`countries.csv`文件。 它位于`src/main/resources`目錄中。 生成應用后,文件將復制到 WAR 的`WEB-INF/classes`目錄。 `com/zetcode/bean/Country.java` ```java package com.zetcode.bean; import com.opencsv.bean.CsvBindByName; import java.util.Objects; public class Country { @CsvBindByName private String name; @CsvBindByName private int population; public Country() { } public Country(String name, int population) { this.name = name; this.population = 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; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Country country = (Country) o; return population == country.population && Objects.equals(name, country.name); } @Override public int hashCode() { return Objects.hash(name, population); } } ``` 這是一個`Country` bean,具有兩個屬性:`name`和`population`。 ```java @CsvBindByName private String name; ``` `@CsvBindByName`將`name`屬性映射到`Name`列中的字段。 `com/zetcode/CountryService.java` ```java package com.zetcode.service; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import com.opencsv.bean.HeaderColumnNameMappingStrategy; import com.zetcode.bean.Country; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; public class CountryService { public static Optional<List<Country>> getListOfCountries() throws IOException { List<Country> countries; try (InputStream is = CountryService.class.getClassLoader() .getResourceAsStream("countries.csv")) { if (is == null) { return Optional.empty(); } HeaderColumnNameMappingStrategy<Country> strategy = new HeaderColumnNameMappingStrategy<>(); strategy.setType(Country.class); try (var br = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8))) { CsvToBean<Country> csvToBean = new CsvToBeanBuilder<Country>(br) .withType(Country.class) .withMappingStrategy(strategy) .withIgnoreLeadingWhiteSpace(true) .build(); countries = csvToBean.parse(); } } return Optional.of(countries); } } ``` `CountryService`從 CSV 文件讀取數據。 ```java try (InputStream is = CountryService.class.getClassLoader() .getResourceAsStream("countries.csv")) { ``` 我們使用`getResourceAsStream()`方法將`InputStream`轉換為`countries.csv`文件。 ```java if (is == null) { return Optional.empty(); } ``` 如果未打開輸入流,則返回空`Optional`。 這用于避免`null`值。 ```java HeaderColumnNameMappingStrategy<Country> strategy = new HeaderColumnNameMappingStrategy<>(); strategy.setType(Country.class); ``` 我們使用 OpenCSV 的`HeaderColumnNameMappingStrategy`將`Country` bean 映射到 CSV 文件中的行。 每行都轉換為一個 bean。 映射是在`@CsvBindByName`注解的幫助下完成的。 ```java try (var br = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8))) { CsvToBean<Country> csvToBean = new CsvToBeanBuilder<Country>(br) .withType(Country.class) .withMappingStrategy(strategy) .withIgnoreLeadingWhiteSpace(true) .build(); countries = csvToBean.parse(); } ``` 使用`CsvToBeanBuilder`,我們解析 CSV 文件并將行轉換為`Country` bean 列表。 `com/zetcode/web/ReadCountries.java` ```java package com.zetcode.web; import com.zetcode.bean.Country; import com.zetcode.service.CountryService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Optional; @WebServlet(name = "ReadCountries", urlPatterns = {"/read"}) public class ReadCountries extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); Optional<List<Country>> countries = CountryService.getListOfCountries(); String templateName; if (countries.isPresent()) { request.setAttribute("countries", countries.get()); templateName = "listCountries.jsp"; } else { templateName = "showError.jsp"; } var dispatcher = request.getRequestDispatcher(templateName); dispatcher.forward(request, response); } } ``` 在`ReadCountries` Servlet 中,我們稱為`getListOfCountries()`服務方法。 如果有一些國家,我們將返回的國家列表設置為`request`對象作為屬性。 處理被傳送到`listCountries.jsp`。 如果找不到數據,則返回錯誤消息。 `webapp/listCountries.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Countries</title> <style> .marked { color: chocolate } </style> </head> <body> <table> <thead> <tr> <th>Country</th> <th>Population</th> </tr> </thead> <tbody> <c:forEach items="${countries}" var="count"> <c:if test="${count.population > 100000000}"> <tr class="marked"> <td> <c:out value="${count.name}"/> </td> <td> <fmt:formatNumber type="number" value="${count.population}" /> </td> </tr> </c:if> <c:if test="${count.population < 100000000}"> <tr> <td> <c:out value="${count.name}"/> </td> <td> <fmt:formatNumber type="number" value="${count.population}" /> </td> </tr> </c:if> </c:forEach> </tbody> </table> </body> </html> ``` 在`listCountries.jsp`文件中,我們在 HTML 表中顯示數據。 ```java <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> ``` 我們使用兩個 JSTL 標簽庫:核心庫和格式庫。 ```java <c:forEach items="${countries}" var="count"> ``` 使用`<c:forEach>`標簽,我們遍歷`countries`對象。 ```java <c:if test="${count.population > 100000000}"> <tr class="marked"> <td> <c:out value="${count.name}"/> </td> <td> <fmt:formatNumber type="number" value="${count.population}" /> </td> </tr> </c:if> ``` 如果該國家/地區的人口超過一億,則使用`marked`類作為行;否則,使用`marked`類作為行。 它以另一種顏色顯示行。 該測試使用 JSTL 的`<c:if>`標簽執行。 `<fmt:formatNumber>`標簽用于格式化該值。 `webapp/index.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>List countries</title> </head> <body> <a href="read">List countries</a> </body> </html> ``` `index.jsp`包含一個調用`ReadCountries` servlet 的鏈接。 Servlet 從 CSV 文件讀取數據,然后將數據以視圖的形式返回給瀏覽器。 `webapp/showError.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> <p>No countries found</p> </body> </html> ``` 此模板文件顯示錯誤消息。 在本教程中,我們展示了如何讀取 WAR 文件中的 CSV 數據。 您可能也對以下相關教程感興趣: [Java 教程](/lang/java/), [Jersey 應用中的 Web URL](/articles/url/) , [Java 驗證教程](/java/validationfilter/)和 [OpenCSV 教程](/articles/opencsv/)。 列出[所有 Java servlet 教程](/all/#servlets)。
                  <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>

                              哎呀哎呀视频在线观看