SpringMVC中文乱码踩坑记录

这篇文章主要介绍了SpringMVC中文乱码踩坑记录,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

问题

使用SpringMVC在返回一个字符串时发生了中文乱码问题。produces属性无效

 @RequestMapping(value = "/nihao", produces = "text/plain;charset=UTF-8") @ResponseBody public String hello(HttpServletResponse response) throws UnsupportedEncodingException { User user = new User(); user.setSex("男"); user.setName("Clover"); user.setAge(19); return user.toString(); }
 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/plain;charset=ISO-8859-1 Content-Length: 36 Date: Sun, 01 Aug 2021 12:20:21 GMT Connection: close { "name": "Clover", "sex": "?", "age": 19 } 

添加常用的过滤器org.springframework.web.filter.CharacterEncodingFilter依然无法解决

  characterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilter encodingutf-8 forceEncodingtrue characterEncodingFilter/*

问题根源

最后查看源码时发现问题出现在处理内容协商的时候,SpringMVC使用了一个叫做org.springframework.http.converter.StringHttpMessageConverter的转换器进行处理java.lang.String。在这个处理器中,有个一默认的编码格式,它甚至使用了final修饰…..

 public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

并且,通过Postman或者REST Client发送请求时,Accept默认是*/*

解决方案

方案一

注册一个StringHttpMessageConverter,注册之后不再使用SpringMVC默认的。它可以将produces设置为Content-Type。也就是说@RequestMappingproduces属性生效了

   
 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Accept-Charset: ... Content-Type: text/plain;charset=utf-8 Content-Length: 37 Date: Sun, 01 Aug 2021 13:09:35 GMT Connection: close { "name": "Clover", "sex": "男", "age": 19 }

方案二

Accept问题,SpringMVC的默认StringHttpMessageConverter处理的是*/*,那手动设置一个Accept尽可能避开它…..

 POST {{url}}/nihao HTTP/1.1 Accept: text/plain;charset=utf-8
 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/plain;charset=utf-8 Content-Length: 38 Date: Sun, 01 Aug 2021 13:20:16 GMT Connection: close { "name": "Clover", "sex": "男", "age": 19 }

以上就是SpringMVC中文乱码踩坑记录的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java