要了解的第一件事是,
RequestMapping#produces()在元素
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
仅用于限制请求处理程序的映射。 它什么也没做。
然后,假设您的方法的返回类型为,
String并带有注释
@ResponseBody,则将通过处理返回值并将
StringHttpMessageConverter其设置
Content-type为
text/plain。如果您想自己返回JSON字符串并将标头设置为
application/json,请使用返回类型
ResponseEntity(摆脱
@ResponseBody)并向其添加适当的标头。
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")public ResponseEntity<String> bar() { final HttpHeaders httpHeaders= new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<String>("{"test": "jsonResponseExample"}", httpHeaders, HttpStatus.OK);}请注意,您可能应该有
<mvc:annotation-driven />
在Servlet上下文配置中使用最合适的默认设置来设置MVC配置。



