title: Stream directly to response output stream in handler method of Spring MVC 3.1 controller
body: <p>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.</p>
  
  <p>I could do the following:</p>
  
  <pre><code>@RequestMapping(method = RequestMethod.POST)
  @ResponseBody
  public String getJson()
  {
      JSONObject rootJson = new JSONObject();
  
      // Populate JSON
  
      return rootJson.toString();
  }
  </code></pre>
  
  <p>But it is inefficient to put together the JSON string, only to have Spring write it to the response's output stream.</p>
  
  <p>Instead, I can write it directly to the response output stream like this:</p>
  
  <pre><code>@RequestMapping(method = RequestMethod.POST)
  public void getJson(HttpServletResponse response)
  {
      JSONObject rootJson = new JSONObject();
  
      // Populate JSON
  
      rootJson.write(response.getWriter());
  }
  </code></pre>
  
  <p>But it seems like there would be a better way to do this than having to resort to passing the <code>HttpServletResponse</code> into the handler method.</p>
  
  <p>Is there another class or interface that can be returned from the handler method that I can use, along with the <code>@ResponseBody</code> annotation?</p>