在学习springmvc 时候,通过注解@ResponseBody注解直接返回一个字符串时,中文全变成???了,网上各种查改这又改那。
我自己写了个过滤器,通过设置contentType等都没有效果
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("========================================");
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("application/json;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
搞了好久才发现,设置根本没有生效(在Controller上设置也没有效果)
最后是通过加produces这个属性修改成功
@RequestMapping(value = "/test/submit",produces = "application/json;charset=utf-8")
或者改为无返回值类型void
@ResponseBody
@RequestMapping(value = "/test/submit")
public void testSubmit(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print("中文不乱了");
}
具体深究我找到一个分析该问题的博主的文章可以传送过去链接