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?
You can have the Output Stream or the Writer as an parameter of your controller method.
@see Spring Reference Documentation 3.1 Chapter 16.3.3.1 Supported method argument types
p.s. I feel that using
OutputStream
orWriter
as an parameter is still much more easier to use in tests than aHttpServletResponse
- and thanks for paying attention to what I have written ;-)In the end, I wrote an
HttpMessageConverter
for this. With it, I can do the following:Here is my
HttpMessageConverter
class:The
HttpMessageConverter
must be registered with Spring. This can be done in thedispatcher-servlet.xml
file like this:As you can see, I have other
HttpMessageConverter
objects registered too. The order does matter.Note that if you use the OutputStream or Writer it requires you to write the headers yourself.
One workaround is to use InputStreamResource/ResourceHttpMessageConverter