<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 JSON 教程 > 原文: [http://zetcode.com/articles/javaservletjson/](http://zetcode.com/articles/javaservletjson/) Java servlet JSON 教程顯示了如何從 Java servlet 返回 JSON 數據。 我們使用 Gson 庫處理 JSON 數據格式。 該 Web 應用已部署在 Tomcat 服務器上。 Apache Tomcat 是由 Apache 軟件基金會(ASF)開發的開源 Java Servlet 容器。 它是最流行的 Java Web 服務器。 Gson 是一個開放源代碼 Java 庫,用于將 Java 對象序列化和反序列化到 JSON 或從 JSON 反序列化。 ## Java Servlet Servlet 是 Java 類,可響應特定類型的網絡請求-最常見的是 HTTP 請求。 Java servlet 用于創建 Web 應用。 它們在 servlet 容器(例如 Tomcat 或 Jetty)中運行。 現代 Java Web 開發使用在 servlet 之上構建的框架。 ## JSON 格式 JSON(JavaScript 對象表示法)是一種輕量級的數據交換格式。 人類很容易讀寫,機器也很容易解析和生成。 JSON 的官方互聯網媒體類型為`application/json`。 JSON 文件擴展名是`.json`。 ## Java Servlet JSON 應用 以下 Web 應用使用 Java Servlet 將數據(城市列表)以 JSON 格式發送到客戶端。 ```java $ tree . ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── bean │ │ │ └── City.java │ │ ├── service │ │ │ └── CityService.java │ │ └── web │ │ └── GetCities.java │ └── webapp │ └── META-INF │ └── context.xml └── 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>ServletJson</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ServletJson</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>4.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> ``` 這是 Maven POM 文件。 我們有兩個工件:用于 Java servlet 的`javax.servlet-api`和用于 Java JSON 處理的`gson`。 `maven-war-plugin`負責收集 Web 應用的所有工件依賴項,類和資源,并將它們打包到 Web 應用存檔(WAR)中。 `context.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <Context path="/ServletJson"/> ``` 在 Tomcat `context.xml`文件中,我們定義了上下文路徑。 它是 Web 應用的名稱。 `City.java` ```java package com.zetcode.bean; import java.util.Objects; public class City { private Long id; private String name; private int population; public City(Long id, String name, int population) { this.id = id; this.name = name; this.population = population; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } 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 int hashCode() { int hash = 3; hash = 97 * hash + Objects.hashCode(this.id); hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + this.population; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final City other = (City) obj; if (this.population != other.population) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return Objects.equals(this.id, other.id); } } ``` 這是`City` bean。 它具有三個屬性:id,名稱和人口。 `GetCities.java` ```java package com.zetcode.web; import com.zetcode.bean.City; import com.zetcode.service.CityService; import com.zetcode.util.JsonConverter; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "GetCities", urlPatterns = {"/GetCities"}) public class GetCities extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); List<City> cities = new CityService().getCities(); JsonConverter converter = new JsonConverter(); String output = converter.convertToJson(cities); out.print(output); } } ``` 這是`GetCities` servlet。 它從服務類檢索數據,并將它們以 JSON 格式返回給客戶端。 ```java response.setContentType("application/json;charset=UTF-8"); ``` 我們將響應對象的內容類型設置為`application/json`。 ```java ServletOutputStream out = response.getOutputStream(); ``` 我們得到了`ServletOutputStream`,用于將數據發送到客戶端。 ```java List<City> cities = new CityService().getCities(); ``` 從`CityService`中,我們可以獲得城市列表。 ```java JsonConverter converter = new JsonConverter(); String output = converter.convertToJson(cities); ``` 我們使用`JsonConverter`將城市列表轉換為 JSON 字符串。 ```java out.print(output); ``` JSON 字符串被寫入`ServletOutputStream`。 `ICityService.java` ```java package com.zetcode.service; import com.zetcode.bean.City; import java.util.List; public interface ICityService { public List<City> getCities(); } ``` `ICityService`包含`getCities()`合同方法。 `CityService.java` ```java package com.zetcode.service; import com.zetcode.bean.City; import com.zetcode.dao.CityDao; import com.zetcode.dao.ICityDao; import java.util.List; public class CityService implements ICityService { ICityDao cityDao; public CityService() { cityDao = new CityDao(); } @Override public List<City> getCities() { return cityDao.findAll(); } } ``` `CityService`的`getCities()`方法返回城市對象的列表。 它使用 DAO 對象訪問數據。 `ICityDao.java` ```java package com.zetcode.dao; import com.zetcode.bean.City; import java.util.List; public interface ICityDao { public List<City> findAll(); } ``` `ICityDao`包含`findAll()`合同方法。 `CityDao.java` ```java package com.zetcode.dao; import com.zetcode.bean.City; import java.util.ArrayList; import java.util.List; public class CityDao implements ICityDao { @Override public List<City> findAll() { List<City> cities = new ArrayList<>(); cities.add(new City(1L, "Bratislava", 432000)); cities.add(new City(2L, "Budapest", 1759000)); cities.add(new City(3L, "Prague", 1280000)); cities.add(new City(4L, "Warsaw", 1748000)); cities.add(new City(5L, "Los Angeles", 3971000)); cities.add(new City(6L, "New York", 8550000)); cities.add(new City(7L, "Edinburgh", 464000)); cities.add(new City(8L, "Berlin", 3671000)); return cities; } } ``` `CityDao`是`ICityDao`的實現。 為簡單起見,我們不連接數據庫。 我們只返回一個城市對象的列表。 `JsonConverter.java` ```java package com.zetcode.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.zetcode.bean.City; import java.util.List; public class JsonConverter { private final Gson gson; public JsonConverter() { gson = new GsonBuilder().create(); } public String convertToJson(List<City> cities) { JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray(); JsonObject jsonObject = new JsonObject(); jsonObject.add("cities", jarray); return jsonObject.toString(); } } ``` `JsonConverter`將城市列表轉換為 JSON 字符串。 我們使用 Gson 庫。 `index.html` ```java <!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <a href="GetCities">GetCities</a> </body> </html> ``` 主頁包含一個調用 servlet 的鏈接。 ## 使用 curl 創建請求 `curl`是使用支持的協議之一從服務器傳輸數據或向服務器傳輸數據的工具。 ```java $ curl localhost:8084/ServletJson/GetCities [{"id":1,"name":"Bratislava","population":432000},{"id":2,"name":"Budapest","population":1759000}, {"id":3,"name":"Prague","population":1280000},{"id":4,"name":"Warsaw","population":1748000}, {"id":5,"name":"Los Angeles","population":3971000},{"id":6,"name":"New York","population":8550000}, {"id":7,"name":"Edinburgh","population":464000},{"id":8,"name":"Berlin","population":3671000}] ``` 這是輸出。 使用`curl`命令,我們向`GetCities` Servlet 發出 HTTP GET 請求。 ## 命名 JSON 數組 如果我們想命名返回的 JSON 數組,可以使用以下代碼: ```java Gson gson = new GsonBuilder().create(); JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray(); JsonObject jsonObject = new JsonObject(); jsonObject.add("cities", jarray); out.print(jsonObject.toString()); ``` 在 Servlet 中,我們將 JSON 數組放入另一個 JSON 對象中,并將屬性命名為`cities`。 在本教程中,我們從 Java servlet 發送了 JSON 數據。 您可能也對以下相關教程感興趣: [Java Servlet RESTful 客戶端](/articles/javaservletrestclient/), [Java Servlet 服務 XML 教程](/articles/javaservletservexml/), [Java Servlet PDF 教程](/articles/javaservletpdf/), [Java RequestDispatcher](/java/requestdispatcher/) ,[從 Java servlet 提供純文本](/articles/javaservlettext/), [Java servlet 復選框教程](/articles/javaservletcheckbox/), [Java servlet 圖像教程](/articles/javaservletimage/), [Java Servlet HTTP 標頭](/articles/javaservlethttpheaders/) 或 [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>

                              哎呀哎呀视频在线观看