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内容的空白屏幕,我错过了教程或评论部分没有留下的内容,谢谢?
答案 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)管理。我不确定你正在关注哪个教程但是它有一些问题:
@WebServlet
进行修饰,而不是使用web.xml中的配置。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
}
}