在Spring MVC 3.1控制器的处理程序方法中直接流到响应输出流

Joh*_*n S 21 spring spring-mvc httpresponse

我有一个控制器方法来处理ajax调用并返回JSON.我正在使用json.org的JSON库来创建JSON.

我可以做以下事情:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getJson()
{
    JSONObject rootJson = new JSONObject();

    // Populate JSON

    return rootJson.toString();
}
Run Code Online (Sandbox Code Playgroud)

但是将JSON字符串放在一起是有效的,只是让Spring将它写入响应的输出流.

相反,我可以将它直接写入响应输出流,如下所示:

@RequestMapping(method = RequestMethod.POST)
public void getJson(HttpServletResponse response)
{
    JSONObject rootJson = new JSONObject();

    // Populate JSON

    rootJson.write(response.getWriter());
}
Run Code Online (Sandbox Code Playgroud)

但似乎有一个更好的方法来做到这一点,而不是诉诸于传递HttpServletResponse给处理程序方法.

是否有另一个类或接口可以从我可以使用的处理程序方法返回,以及@ResponseBody注释?

Ral*_*lph 31

您可以将Output Stream或Writer作为控制器方法的参数.

@RequestMapping(method = RequestMethod.POST)
public void getJson(Writer responseWriter) {
    JSONObject rootJson = new JSONObject();
    rootJson.write(responseWriter);
}
Run Code Online (Sandbox Code Playgroud)

@see Spring Reference Documentation 3.1第16.3.3.1节支持的方法参数类型

ps我觉得使用OutputStreamWriter作为参数在测试中使用起来比使用它更容易HttpServletResponse- 并且感谢关注我所写的内容 ;-)