原文: 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 格式发送到客户端。

  1. $ tree
  2. .
  3. ├── pom.xml
  4. └── src
  5. ├── main
  6. ├── java
  7. └── com
  8. └── zetcode
  9. ├── bean
  10. └── City.java
  11. ├── service
  12. └── CityService.java
  13. └── web
  14. └── GetCities.java
  15. └── webapp
  16. └── META-INF
  17. └── context.xml
  18. └── test
  19. └── java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>ServletJson</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <name>ServletJson</name>
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <maven.compiler.source>1.8</maven.compiler.source>
  15. <maven.compiler.target>1.8</maven.compiler.target>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>javax.servlet</groupId>
  20. <artifactId>javax.servlet-api</artifactId>
  21. <version>4.0.0</version>
  22. <scope>provided</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.google.code.gson</groupId>
  26. <artifactId>gson</artifactId>
  27. <version>2.8.2</version>
  28. </dependency>
  29. </dependencies>
  30. <build>
  31. <plugins>
  32. <plugin>
  33. <groupId>org.apache.maven.plugins</groupId>
  34. <artifactId>maven-war-plugin</artifactId>
  35. <version>2.6</version>
  36. <configuration>
  37. <failOnMissingWebXml>false</failOnMissingWebXml>
  38. </configuration>
  39. </plugin>
  40. </plugins>
  41. </build>
  42. </project>

这是 Maven POM 文件。 我们有两个工件:用于 Java servlet 的javax.servlet-api和用于 Java JSON 处理的gsonmaven-war-plugin负责收集 Web 应用的所有工件依赖项,类和资源,并将它们打包到 Web 应用存档(WAR)中。

context.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Context path="/ServletJson"/>

在 Tomcat context.xml文件中,我们定义了上下文路径。 它是 Web 应用的名称。

City.java

  1. package com.zetcode.bean;
  2. import java.util.Objects;
  3. public class City {
  4. private Long id;
  5. private String name;
  6. private int population;
  7. public City(Long id, String name, int population) {
  8. this.id = id;
  9. this.name = name;
  10. this.population = population;
  11. }
  12. public Long getId() {
  13. return id;
  14. }
  15. public void setId(Long id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public int getPopulation() {
  25. return population;
  26. }
  27. public void setPopulation(int population) {
  28. this.population = population;
  29. }
  30. @Override
  31. public int hashCode() {
  32. int hash = 3;
  33. hash = 97 * hash + Objects.hashCode(this.id);
  34. hash = 97 * hash + Objects.hashCode(this.name);
  35. hash = 97 * hash + this.population;
  36. return hash;
  37. }
  38. @Override
  39. public boolean equals(Object obj) {
  40. if (this == obj) {
  41. return true;
  42. }
  43. if (obj == null) {
  44. return false;
  45. }
  46. if (getClass() != obj.getClass()) {
  47. return false;
  48. }
  49. final City other = (City) obj;
  50. if (this.population != other.population) {
  51. return false;
  52. }
  53. if (!Objects.equals(this.name, other.name)) {
  54. return false;
  55. }
  56. return Objects.equals(this.id, other.id);
  57. }
  58. }

这是City bean。 它具有三个属性:id,名称和人口。

GetCities.java

  1. package com.zetcode.web;
  2. import com.zetcode.bean.City;
  3. import com.zetcode.service.CityService;
  4. import com.zetcode.util.JsonConverter;
  5. import java.io.IOException;
  6. import java.util.List;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.annotation.WebServlet;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. @WebServlet(name = "GetCities", urlPatterns = {"/GetCities"})
  14. public class GetCities extends HttpServlet {
  15. @Override
  16. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  17. throws ServletException, IOException {
  18. response.setContentType("application/json;charset=UTF-8");
  19. ServletOutputStream out = response.getOutputStream();
  20. List<City> cities = new CityService().getCities();
  21. JsonConverter converter = new JsonConverter();
  22. String output = converter.convertToJson(cities);
  23. out.print(output);
  24. }
  25. }

这是GetCities servlet。 它从服务类检索数据,并将它们以 JSON 格式返回给客户端。

  1. response.setContentType("application/json;charset=UTF-8");

我们将响应对象的内容类型设置为application/json

  1. ServletOutputStream out = response.getOutputStream();

我们得到了ServletOutputStream,用于将数据发送到客户端。

  1. List<City> cities = new CityService().getCities();

CityService中,我们可以获得城市列表。

  1. JsonConverter converter = new JsonConverter();
  2. String output = converter.convertToJson(cities);

我们使用JsonConverter将城市列表转换为 JSON 字符串。

  1. out.print(output);

JSON 字符串被写入ServletOutputStream

ICityService.java

  1. package com.zetcode.service;
  2. import com.zetcode.bean.City;
  3. import java.util.List;
  4. public interface ICityService {
  5. public List<City> getCities();
  6. }

ICityService包含getCities()合同方法。

CityService.java

  1. package com.zetcode.service;
  2. import com.zetcode.bean.City;
  3. import com.zetcode.dao.CityDao;
  4. import com.zetcode.dao.ICityDao;
  5. import java.util.List;
  6. public class CityService implements ICityService {
  7. ICityDao cityDao;
  8. public CityService() {
  9. cityDao = new CityDao();
  10. }
  11. @Override
  12. public List<City> getCities() {
  13. return cityDao.findAll();
  14. }
  15. }

CityServicegetCities()方法返回城市对象的列表。 它使用 DAO 对象访问数据。

ICityDao.java

  1. package com.zetcode.dao;
  2. import com.zetcode.bean.City;
  3. import java.util.List;
  4. public interface ICityDao {
  5. public List<City> findAll();
  6. }

ICityDao包含findAll()合同方法。

CityDao.java

  1. package com.zetcode.dao;
  2. import com.zetcode.bean.City;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class CityDao implements ICityDao {
  6. @Override
  7. public List<City> findAll() {
  8. List<City> cities = new ArrayList<>();
  9. cities.add(new City(1L, "Bratislava", 432000));
  10. cities.add(new City(2L, "Budapest", 1759000));
  11. cities.add(new City(3L, "Prague", 1280000));
  12. cities.add(new City(4L, "Warsaw", 1748000));
  13. cities.add(new City(5L, "Los Angeles", 3971000));
  14. cities.add(new City(6L, "New York", 8550000));
  15. cities.add(new City(7L, "Edinburgh", 464000));
  16. cities.add(new City(8L, "Berlin", 3671000));
  17. return cities;
  18. }
  19. }

CityDaoICityDao的实现。 为简单起见,我们不连接数据库。 我们只返回一个城市对象的列表。

JsonConverter.java

  1. package com.zetcode.util;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. import com.google.gson.JsonArray;
  5. import com.google.gson.JsonObject;
  6. import com.zetcode.bean.City;
  7. import java.util.List;
  8. public class JsonConverter {
  9. private final Gson gson;
  10. public JsonConverter() {
  11. gson = new GsonBuilder().create();
  12. }
  13. public String convertToJson(List<City> cities) {
  14. JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray();
  15. JsonObject jsonObject = new JsonObject();
  16. jsonObject.add("cities", jarray);
  17. return jsonObject.toString();
  18. }
  19. }

JsonConverter将城市列表转换为 JSON 字符串。 我们使用 Gson 库。

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Home page</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <a href="GetCities">GetCities</a>
  10. </body>
  11. </html>

主页包含一个调用 servlet 的链接。

使用 curl 创建请求

curl是使用支持的协议之一从服务器传输数据或向服务器传输数据的工具。

  1. $ curl localhost:8084/ServletJson/GetCities
  2. [{"id":1,"name":"Bratislava","population":432000},{"id":2,"name":"Budapest","population":1759000},
  3. {"id":3,"name":"Prague","population":1280000},{"id":4,"name":"Warsaw","population":1748000},
  4. {"id":5,"name":"Los Angeles","population":3971000},{"id":6,"name":"New York","population":8550000},
  5. {"id":7,"name":"Edinburgh","population":464000},{"id":8,"name":"Berlin","population":3671000}]

这是输出。 使用curl命令,我们向GetCities Servlet 发出 HTTP GET 请求。

命名 JSON 数组

如果我们想命名返回的 JSON 数组,可以使用以下代码:

  1. Gson gson = new GsonBuilder().create();
  2. JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray();
  3. JsonObject jsonObject = new JsonObject();
  4. jsonObject.add("cities", jarray);
  5. out.print(jsonObject.toString());

在 Servlet 中,我们将 JSON 数组放入另一个 JSON 对象中,并将属性命名为cities

在本教程中,我们从 Java servlet 发送了 JSON 数据。

您可能也对以下相关教程感兴趣: Java Servlet RESTful 客户端Java Servlet 服务 XML 教程Java Servlet PDF 教程Java RequestDispatcher从 Java servlet 提供纯文本Java servlet 复选框教程Java servlet 图像教程Java Servlet HTTP 标头Java 教程