JSON 输出显示在 Java Servlet 上

JSON output showing on Java Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject;

  // Extend HttpServlet class
  public class Test extends HttpServlet {
  JSONObject json = new JSONObject();

  public void init() throws ServletException
  {
     json.put("city", "Mumbai");
     json.put("country", "India");
  }

  public void doGet(HttpServletRequest request,
                HttpServletResponse response)
       throws ServletException, IOException
  {
       response.setContentType("application/json");
       String output = json.toString();
  }

  public void destroy()
  {
      //do nothing
  }
}

您好,我正在按照在线教程创建此 servlet class,它在 Apache Tomcat 上 运行ning。当我 运行 class 我得到一个没有 json 内容的空白屏幕时,我是否遗漏了什么教程或评论部分没有任何内容,谢谢?

您需要在响应流中写入 JSON 对象的内容。方法如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("application/json");
    String output = json.toString();
    PrintWriter writer = response.getWriter();
    writer.write(output);
    writer.close();
}

此外,在您的 Servlet 中声明非最终对象是一种不好的做法,除非它们由 EJB 或数据源等应用程序服务器管理。我不确定您正在学习哪个教程,但它存在一些问题:

  1. 我们使用的是 Servlet 3.1,可以用 @WebServlet 修饰 servlet,而不是使用 web.xml 中的配置。
  2. 由于并发问题,您应该避免在 Servlet 中声明非最终字段。当通过对 servlet 的 GET 或 POST 调用更新字段并且多个(2 个或更多)客户端同时对 servlet 执行相同的调用时,可以注意到这一点,这将以奇怪的结果结束servlet 的客户端。
  3. 如果您want/need获取数据以在 Servlet 中使用,您应该在尽可能窄的范围内获取它。对于 Servlet,这意味着您应该使用 doXXX 方法之一获取数据。

您的代码示例应如下所示:

@WebServlet("/path")
public class Test extends HttpServlet {
    //avoid declaring it here unless it's final
    //JSONObject json = new JSONObject();

    public void init() throws ServletException {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        //check that now JSONObject was moved as local variable
        //for this method and it's initialized with the result
        //of a method called retrieveData
        //in this way, you gain several things:
        //1. Reusability: code won't be duplicated along multiple classes
        //   clients of this service
        //2. Maintainability: centralize how and from where you will
        //   retrieve the data.
        JSONObject json = retrieveData();

        response.setContentType("application/json");
        String output = json.toString();
        PrintWriter writer = response.getWriter();
        writer.write(output);
        writer.close();
    }

    //this method will be in charge to return the data you want/need
    //for learning purposes, you're hardcoding the data
    //in real world applications, you have to retrieve the data
    //from a datasource like a file or a database
    private JSONObject retrieveData() {
        //Initializing the object to return
        JSONObject json = new JSONObject();
        //filling the object with data
        //again, you're hardcoding it for learning/testing purposes
        //this method can be modified to obtain data from
        //an external resource
        json.put("city", "Mumbai");
        json.put("country", "India");
        //returning the object
        return json;
    }

    public void destroy() {
        //do nothing
    }
}