@Controller @RequestMapping(value="/user") public class UserController { @RequestMapping(value = "/profile/{id}", method = RequestMethod.GET) public @ResponseBody String profile(@PathVariable("id") int id){ // ... } }
从 debug 信息中可以看到
17:32:44.772 [nioEventLoopGroup-3-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Written [{"info":{"error":0,"success":true}}] as "text/plain;charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@7fc3baf5]
输出的内容默认是text/plain;charset=ISO-8859-1
写入缓冲区的,虽然我在最后输出时修改了
response.headers().set(CONTENT_TYPE, "application/json;charset=UTF-8");
但是还是存在,写入的时候格式不对的情况。
可以通过如下方法保证该@Controller
下的所有方法都输出 json 格式
@Controller @RequestMapping(value="/user",produces = "application/json;charset=UTF-8") public class UserController { @RequestMapping(value = "/profile/{id}", method = RequestMethod.GET) public @ResponseBody String profile(@PathVariable("id") int id){ // ... } }
👇 下面是我的公众号,高质量的博文我会第一时间同步到公众号,给个关注吧!