我有一个返回 JSON 字符串的 Spring MVC Controller ,我想将 mimetype 设置为 application/json。我该怎么做?
@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
return myService.getJson();
}
业务对象已作为 JSON 字符串提供,因此使用 MappingJacksonJsonView
不是我的解决方案。 @ResponseBody
已经很完美了,但是如何设置 mimetype 呢?
最佳答案
使用 ResponseEntity
而不是 ResponseBody
。这样您就可以访问响应 header ,并且可以设置适当的内容类型。根据Spring docs :
The
HttpEntity
is similar to@RequestBody
and@ResponseBody
. Besides getting access to the request and response body,HttpEntity
(and the response-specific subclassResponseEntity
) also allows access to the request and response headers
代码如下:
@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
String json = "jsonResponse";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
关于java - 在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4471584/