使用JSON响应的Java Web服务器

时间:2017-08-14 22:25:27

标签: java json http servlets

我正在尝试创建一个简单的java web-app,它使用JSON字符串对/ test进行GET请求。

我的环境是Java,Intellij和Tomcat 8.5.4。

到目前为止,我已经有3个班级了:

  • CSV - 用于CSV到JSON转换
  • CleanUp - 实际转换数据的类
  • Servlet - 响应GET请求的类

我的Servlet课程:

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;


@WebServlet(name = "Servlet")
public class Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("GET request received");
    CleanUp cleanup = new CleanUp();
    cleanup.cleanupData();

    // Logic needed here to send the data to client

    }
}

CleanUp类当前将结果数据发送到控制台,如:

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(System.out, list);

我是新的,甚至不确定我想要的是否可以作为javax.http.servlet的一部分完成,还是需要另一个依赖?

2 个答案:

答案 0 :(得分:1)

您的解决方案无疑对您有用,但将来您可能需要按以下方式更新:

public class Cleanup {
  ...

  public void cleanupData(Writer output) {
     ObjectMapper mapper = new ObjectMapper();
     mapper.enable(SerializationFeature.INDENT_OUTPUT);
     mapper.writeValue(output, list);
  } 

  ...
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Get Response");
    response.setContentType("application/json");
    ConvertCSV cleanup = new ConvertCSV();
    String outputData = cleanup.cleanupData(response.getWriter());
    ...

正确设置内容类型将使Javascript更容易处理响应,而不会被浏览器破坏(因为你告诉它它的HTML)。

其次,将JSON直接写入响应将提高servlet的可伸缩性,因为它消除了您在String变量中创建的JSON的副本。如果您的JSON很短,那么这并没有多大区别,但想象一下cleanupData是否会产生大量输出,例如当list包含1000个条目时。

答案 1 :(得分:0)

答案是首先将输出数据存储在String对象中;

outputData = mapper.writeValueAsString(list);

然后在servlet中:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Get Response");
    ConvertCSV cleanup = new ConvertCSV();
    String outputData = cleanup.cleanupData();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(outputData);
    out.close();
}