我正在尝试在 Spring WebMVC 3.0.5 控制器中使用 ResponseEntity 返回类型。我要返回图像,因此我想使用以下代码将内容类型设置为 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 吗?
另一个提议:
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_GIF)
.body(resource);
尝试注入 HttpServletResponse 对象并从那里强制内容类型。
@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);
}
这应该是设置所有参数(如 httpStatus 、 contentType 和 body )的方法
ResponseEntity.status(状态).contentType(MediaType.APPLICATION_JSON).body(响应);
此示例使用 ResponseEntity.BodyBuilder 接口。
这两种做法都是正确的。您还可以使用
ResponseEntity<?>
位于顶部,以便您可以发送多种类型的数据。