I am trying to use the ResponseEntity return type in my Spring WebMVC 3.0.5 controller. I am returning an image, so I want to set the Content Type to image/gif with the following code:
@RequestMapping(value="/*.gif")
public ResponseEntity<Resource> sendGif() throws FileNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_GIF);
return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
}
However, the return type is being overridden to text/html in ResourceHttpMessageConverter.
Other than implementing my own HttpMessageConverter and injecting this into the AnnotationMethodHandlerAdapter, is there any way for me to force the Content-Type?
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.
A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.
ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.
Another proposition :
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_GIF)
.body(resource);
try injecting the HttpServletResponse object and force the content type from there.
@RequestMapping(value="/*.gif")
public ResponseEntity<Resource> sendGif(final HttpServletResponse response) throws FileNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_GIF);
response.setContentType("image/gif"); // set the content type
return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With