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 格式发送到客户端。
$ 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
<?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.0http://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
<?xml version="1.0" encoding="UTF-8"?><Context path="/ServletJson"/>
在 Tomcat context.xml文件中,我们定义了上下文路径。 它是 Web 应用的名称。
City.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;}@Overridepublic 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;}@Overridepublic 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
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 {@Overrideprotected 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 格式返回给客户端。
response.setContentType("application/json;charset=UTF-8");
我们将响应对象的内容类型设置为application/json。
ServletOutputStream out = response.getOutputStream();
我们得到了ServletOutputStream,用于将数据发送到客户端。
List<City> cities = new CityService().getCities();
从CityService中,我们可以获得城市列表。
JsonConverter converter = new JsonConverter();String output = converter.convertToJson(cities);
我们使用JsonConverter将城市列表转换为 JSON 字符串。
out.print(output);
JSON 字符串被写入ServletOutputStream。
ICityService.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
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();}@Overridepublic List<City> getCities() {return cityDao.findAll();}}
CityService的getCities()方法返回城市对象的列表。 它使用 DAO 对象访问数据。
ICityDao.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
package com.zetcode.dao;import com.zetcode.bean.City;import java.util.ArrayList;import java.util.List;public class CityDao implements ICityDao {@Overridepublic 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
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
<!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是使用支持的协议之一从服务器传输数据或向服务器传输数据的工具。
$ 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 数组,可以使用以下代码:
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 客户端, Java Servlet 服务 XML 教程, Java Servlet PDF 教程, Java RequestDispatcher ,从 Java servlet 提供纯文本, Java servlet 复选框教程, Java servlet 图像教程, Java Servlet HTTP 标头 或 Java 教程
