在Spring MVC 3.1控制器的处理程序方法中直接流式传输到响应输出流
问题内容:
我有一个控制器方法来处理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
方法传递给处理程序方法更好的方法。
是否可以从我可以使用的处理程序方法以及@ResponseBody
注释中返回其他类或接口?
问题答案:
您可以将输出流或编写器作为控制器方法的参数。
@RequestMapping(method = RequestMethod.POST)
public void getJson(Writer responseWriter) {
JSONObject rootJson = new JSONObject();
rootJson.write(responseWriter);
}
@see
Spring参考文档3.1第16.3.3.1章支持的方法参数类型
ps我觉得使用a
OutputStream
或Writer
作为参数仍然比a更容易在测试中使用HttpServletResponse
-感谢您关注我写的内容
;-)