我有一个 Controller 方法来处理 ajax 调用并返回 JSON。我正在使用来自 json.org 的 JSON 库来创建 JSON。
我可以做到以下几点:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getJson()
{
JSONObject rootJson = new JSONObject();
// Populate JSON
return rootJson.toString();
}
但是将 JSON 字符串放在一起是低效的,只是让 Spring 将其写入响应的输出流。
相反,我可以像这样直接将其写入响应输出流:
@RequestMapping(method = RequestMethod.POST)
public void getJson(HttpServletResponse response)
{
JSONObject rootJson = new JSONObject();
// Populate JSON
rootJson.write(response.getWriter());
}
但似乎有比将 HttpServletResponse
传递给处理程序方法更好的方法。
是否有另一个类或接口(interface)可以从我可以使用的处理程序方法返回,以及 @ResponseBody
注释?
最佳答案
您可以将输出流或写入器作为 Controller 方法的参数。
@RequestMapping(method = RequestMethod.POST)
public void getJson(Writer responseWriter) {
JSONObject rootJson = new JSONObject();
rootJson.write(responseWriter);
}
@见 Spring Reference Documentation 3.1 Chapter 16.3.3.1 Supported method argument types
附言我觉得使用 OutputStream
或 Writer
作为参数在测试中仍然比 HttpServletResponse
更容易使用 - 感谢您的关注what I have written ;-)
关于spring - 在 Spring MVC 3.1 Controller 的处理程序方法中直接流到响应输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283347/