Stream directly to response output stream in handler method of Spring MVC 3.1 controller

John S picture John S · Mar 7, 2013 · Viewed 32.3k times · Source

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.

I could do the following:

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

    // Populate JSON

    return rootJson.toString();
}

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());
}

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.

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

Answer

Ralph picture Ralph · Mar 8, 2013

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);
}

@see Spring Reference Documentation 3.1 Chapter 16.3.3.1 Supported method argument types

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 ;-)