Spring Web MVC: How to use a ResponseEntity in the view class, not the controller?
Using Spring Web MVC, I would like to use a ResponseEntity to send bytes back to the client.
For example, I could do this:
@RequestMapping(value = "/getMyBytes", method = RequestMethod.GET)
public ResponseEntity< byte[] > handleGetMyBytesRequest()
{
// Get bytes from somewhere...
byte[] byteData = ....
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType( MediaType.IMAGE_PNG );
responseHeaders.setContentLength( byteData.length );
return new ResponseEntity< byte[] >( byteData,
responseHeaders, HttpStatus.OK );
}
But now the controller itself decides, how the data will be presented to the client. Shouldn't that not be the job of the view?
So my question is, when I have this view class:
public class DemoView extends AbstractView
{
@Override
protected void renderMergedOutputModel( Map< String, Object > model,
HttpServletRequest request, HttpServletResponse response ) throws Exception
{
bytes[] byteData = model.get( "byteData" );
// ???
}
}
How must the view code look like, when I want to use a ResponseEntity there?
Or does it make no sense to use ResponseEntity in the vi开发者_如何学Goew class, and if yes, why?
Thanks a lot for your help!
In your AbstractView
you can simply use the HttpServletResponse
object to set the HTTP response status and write the byte[]
array to the output stream:
response.setStatus(status);
response.getOutputStream().write(byteData);
精彩评论