Java Servlet上显示的JSON输出

时间:2015-01-23 14:31:38

标签: 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类。当我运行课程时,我得到一个没有json内容的空白屏幕,我错过了教程或评论部分没有留下的内容,谢谢?

1 个答案:

答案 0 :(得分:4)

您需要在响应流中编写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或DataSources)管理。我不确定你正在关注哪个教程但是它有一些问题:

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

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