1. Introduction
1.绪论
In this quick tutorial, we’ll create a small web application and explore how to return a JSON response from a Servlet.
在这个快速教程中,我们将创建一个小型Web应用程序,并探讨如何从Servlet返回JSON响应。
2. Maven
2.雯雯
For our web application, we’ll include javax.servlet-api and Gson dependencies in our pom.xml:
对于我们的Web应用程序,我们将在javax.servlet-api和Gson的依赖中包含pom.xml。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
The latest versions of the dependencies can be found here: javax.servlet-api and gson.
最新版本的依赖项可以在这里找到。javax.servlet-api和gson。
We also need to configure a Servlet container to deploy our application to. This article is a good place to start on how to deploy a WAR on Tomcat.
我们还需要配置一个Servlet容器,将我们的应用程序部署到其中。这篇文章是了解如何在Tomcat上部署WAR的一个好地方。
3. Creating an Entity
3.创建一个实体
Let’s create an Employee entity which will later be returned from the Servlet as JSON:
让我们创建一个Employee实体,该实体随后将从Servlet返回为JSON。
public class Employee {
private int id;
private String name;
private String department;
private long salary;
// constructors
// standard getters and setters.
}
4. Entity to JSON
4.实体到JSON
To send a JSON response from the Servlet we first need to convert the Employee object into its JSON representation.
为了从Servlet发送JSON响应,我们首先需要将Employee对象转换为JSON表示。
There are many java libraries available to convert an object to there JSON representation and vice versa. Most prominent of them would be the Gson and Jackson libraries. To learn about the differences between GSON and Jackson, have a look at this article.
有许多java库可以将一个对象转换为JSON表示,反之亦然。其中最突出的是Gson和Jackson库。要了解GSON和Jackson之间的区别,请看这篇文章。
A quick sample for converting an object to JSON representation with Gson would be:
用Gson将一个对象转换为JSON表示法的一个快速例子是。
String employeeJsonString = new Gson().toJson(employee);
5. Response and Content Type
5.响应和内容类型
For HTTP Servlets, the correct procedure for populating the response:
对于HTTP Servlets,正确的程序是填充响应。
- Retrieve an output stream from the response
- Fill in the response headers
- Write content to the output stream
- Commit the response
In a response, a Content-Type header tells the client what the content type of the returned content actually is.
在一个响应中,Content-Type头告诉客户端返回内容的内容类型究竟是什么。
For producing a JSON response the content type should be application/json:
对于产生JSON响应,内容类型应该是application/json:。
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();
Response headers must always be set before the response is committed. The web container will ignore any attempt to set or add headers after the response is committed.
响应头必须总是在响应提交之前设置。Web 容器将忽略任何在响应提交后设置或添加头信息的尝试。
Calling flush() on the PrintWriter commits the response.
在PrintWriter上调用flush()会提交响应。
6. Example Servlet
6.服务器实例
Now let’s see an example Servlet that returns a JSON response:
现在让我们看看一个返回JSON响应的Servlet的例子。
@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
public class EmployeeServlet extends HttpServlet {
private Gson gson = new Gson();
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws IOException {
Employee employee = new Employee(1, "Karan", "IT", 5000);
String employeeJsonString = this.gson.toJson(employee);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();
}
}
7. Conclusion
7.结语
This article showcased how to return a JSON response from a Servlet. This is helpful in web applications that use Servlets to implement REST Services.
这篇文章展示了如何从Servlet返回JSON响应。这对于使用Servlet来实现REST服务的Web应用程序很有帮助。
All code samples shown here can be found on GitHub.