在Spring MVC 3.1控制器的处理程序方法中直接流式传输到响应输出流 [英] Stream directly to response output stream in handler method of Spring MVC 3.1 controller

查看:187
本文介绍了在Spring MVC 3.1控制器的处理程序方法中直接流式传输到响应输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a controller method that handles ajax calls and returns JSON. I am using the JSON library from json.org to create the JSON.

我可以执行以下操作:

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

    // Populate JSON

    return rootJson.toString();
}

但是将JSON字符串组合在一起效率很低,只是让Spring将其写入响应的输出流中.

But it is inefficient to put together the JSON string, only to have Spring write it to the response's output stream.

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

Instead, I can write it directly to the response output stream like this:

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

    // Populate JSON

    rootJson.write(response.getWriter());
}

但是,似乎有比通过将HttpServletResponse传递到处理程序方法更好的方法了.

But it seems like there would be a better way to do this than having to resort to passing the HttpServletResponse into the handler method.

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

Is there another class or interface that can be returned from the handler method that I can use, along with the @ResponseBody annotation?

推荐答案

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

You can have the Output Stream or the Writer as an parameter of your controller method.

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

@请参见 p.s.我觉得在测试中使用OutputStreamWriter作为参数仍然比HttpServletResponse更容易使用-感谢您关注

p.s. I feel that using OutputStream or Writer as an parameter is still much more easier to use in tests than a HttpServletResponse - and thanks for paying attention to what I have written ;-)

这篇关于在Spring MVC 3.1控制器的处理程序方法中直接流式传输到响应输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆