我尝试在Spring WebMVC 3.0.5控制器中使用ResponseEntity返回类型。我返回一个image,所以我想使用以下代码将Content Type设置为image/gif:
@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);
}
字符串
但是,在ResourceHttpMessageConverter中,返回类型被重写为text/html。
除了实现我自己的HttpMessageConverter并将其注入AnnotationMethodHandlerAdapter之外,还有什么方法可以强制使用Content-Type吗?
4条答案
按热度按时间mfpqipee1#
另一个提议:
字符串
atmip9wb2#
尝试注入HttpServletResponse对象并从那里强制内容类型。
字符串
kxxlusnw3#
这应该是设置httpStatus、contentType和body等所有参数的方法
ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(response);
此示例使用ResponseEntity.BodyBuilder接口。
wvmv3b1j4#
这两种方法都是正确的。你也可以在顶部使用
ResponseEntity<?>
,这样你就可以发送多种类型的数据。