java - Java Servlet 上显示的 JSON 输出

标签 java json servlets

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
  }
}

您好,我按照在线教程创建了这个在 Apache Tomcat 上运行的 servlet 类。当我运行类(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,servlet 可以用 @WebServlet 修饰,而不是在 web.xml 中使用配置。
  2. 由于并发问题,您应该避免在 Servlet 中声明非最终字段。当通过对 servlet 的 GET 或 POST 调用更新字段并且多个(2 个或更多)客户端同时对 servlet 执行相同的调用时,可以注意到这一点,这将导致 servlet 的客户端出现奇怪的结果.
  3. 如果您想要/需要获取数据以在 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
    }
}

关于java - Java Servlet 上显示的 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28112093/

相关文章:

multithreading - Servlet Multi-Threading,创建工作线程的地方

servlets - 我正在寻找一种使用 JSch 创建异步和无状态 ssh 连接的方法?

Java 时区转换产生相反的结果。

java - TreeSet 和 HashSet 中的 addAll 究竟是如何工作的?

java - 如何让任意IP地址连接到远程MySQL服务器?

javascript - 循环每个输入的相对记录并纠正重复记录

java - 一个 servlet java 中的多个操作 (CRUD)

java - 无法找到或加载主类 osx 终端

c# - 使用 ServiceStack.Text : determine JSON is Array, 对象或字符串?

javascript - 为什么我的双引号作为单引号收到?