spring 使用ResponseEntity发送自定义Content-Type< Resource>

tzcvj98z  于 2023-11-16  发布在  Spring
关注(0)|答案(4)|浏览(209)

我尝试在Spring WebMVC 3.0.5控制器中使用ResponseEntity返回类型。我返回一个image,所以我想使用以下代码将Content Type设置为image/gif:

  1. @RequestMapping(value="/*.gif")
  2. public ResponseEntity<Resource> sendGif() throws FileNotFoundException {
  3. HttpHeaders headers = new HttpHeaders();
  4. headers.setContentType(MediaType.IMAGE_GIF);
  5. return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
  6. }

字符串
但是,在ResourceHttpMessageConverter中,返回类型被重写为text/html。
除了实现我自己的HttpMessageConverter并将其注入AnnotationMethodHandlerAdapter之外,还有什么方法可以强制使用Content-Type吗?

mfpqipee

mfpqipee1#

另一个提议:

  1. return ResponseEntity
  2. .ok()
  3. .contentType(MediaType.IMAGE_GIF)
  4. .body(resource);

字符串

atmip9wb

atmip9wb2#

尝试注入HttpServletResponse对象并从那里强制内容类型。

  1. @RequestMapping(value="/*.gif")
  2. public ResponseEntity<Resource> sendGif(final HttpServletResponse response) throws FileNotFoundException {
  3. HttpHeaders headers = new HttpHeaders();
  4. headers.setContentType(MediaType.IMAGE_GIF);
  5. response.setContentType("image/gif"); // set the content type
  6. return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
  7. }

字符串

kxxlusnw

kxxlusnw3#

这应该是设置httpStatus、contentType和body等所有参数的方法
ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(response);
此示例使用ResponseEntity.BodyBuilder接口。

wvmv3b1j

wvmv3b1j4#

这两种方法都是正确的。你也可以在顶部使用ResponseEntity<?>,这样你就可以发送多种类型的数据。

相关问题