问题
这里驾驶不能使用注解@ResponseBody
,想要在响应头中设置返回json返回。
解决
添加xml配置
<mvc:annotation-driven />
添加HttpHeaders设置
@RequestMapping(value = "/json", method = RequestMethod.GET)
public ResponseEntity<String> bar() {
final HttpHeaders httpHeaders= new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}
**注意:**这里没有使用注解@ResponseBody
。 还应该了解如下代码不会生效:
// 无效设置
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
final HttpHeaders httpHeaders= new HttpHeaders();
return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}
这里只是对请求的约束,并不是会响应的约束,参考文档RequestMapping#produces()
。
参考: Spring MVC 4: “application/json” Content Type is not being set correctly