记一次SpringBoot返回数据乱码引发的思考
文章目录
问题背景
使用SpringBoot的starter构建了一个demo项目,添加了一个Get接口,返回一段字符串,有中文、数字和英文,接口一直正常,直到昨天在项目添加了Listener、Filter和Interceptor,接口返回的中文乱码了。
解决过程
-
添加完Listener、Filter和Interceptor(内部都只打印日志,无业务逻辑)后请求接口返回如下:
-
将代码回滚后,显示正常:
-
Debug到
AbstractMessageConverterMethodProcessor
中,发现StringHttpMessageConverter
在write body时用的字符集为ISO-8859-1
,修改defaultCharset
为UTF-8
后显示正常; -
搜索HttpMessageConverters的相关资料:
- 修改Spring初始化后的StringHttpMessageConverter的默认字符集为
UTF-8
。
解决方案:
一、指定本请求产生的Response的内容格式
在@RequestMapping
中设置produce:@RequestMapping(value = "/config",produces = {"text/html;charset=UTF-8"})
二、修改Spring的StringHttpMessageConverter
默认字符集
@Configuration
public class WebMvcConfigure extends WebMvcConfigurationSupport {
/* 该方法不建议使用,因为此方法接管了Spring初始化时对HttpMessageConverters的初始化过程,接管以后,Spring不再对此进行初始化
* 该方法在 extendMessageConverters 之前执行
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add