Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 914
John S Avatar asked Mar 07 '13 22:03

John S


1 Answers

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

like image 118
Ralph Avatar answered Oct 06 '22 07:10

Ralph