在使用SSM框架写代码时,偶然间在console控制台发现一个"text/plain;charset=ISO-8859-1"这种数据格式,如下图
当时就感觉有点问题,因为我的项目中使用UTF-8的编码格式,并且在web.xml 中也采用了utf-8的编码过滤,如下图。
但是出现这种情况很不理解,多方百度AbstractMessageConverterMethodProcessor无果,便放弃。
然而在今天需要返回JSON数据时出现中文乱码,发现还是之前发现的问题,接着百度查找答案。。。
错误描述
使用@RequestMapping返回JSON格式时,中文出现问号乱码,如下图前台获取的JSON数据,图中出现的问号是中文,没有编译出。
注:正确的返回JSON数据应该是:
["com.song.model.User@47755c88账号:admin密码:8f61b106154bbc39cd8c2334c046bb62权限:2校验码:NTY0session中的校验码:NTY0"]
查看到request和response的响应报文编码如下
错误原因
在SSM框架中,我才用的是spring-mvc4.0版本,在其对应的org.springframework.http.converter.StringHttpMessageConverter方法中使用的是默认字符集是ISO-8859-1编码,如图
需要将StringHttpMessageConverter的编码方式改为UTF-8.
解决方案
方式一、
在@RequestMapping里面加入produces = "text/html;charset=UTF-8"
测试结果:
采用这种方案,需要在每个@RequestMapping中都加入produces = "text/html;charset=UTF-8" 比较麻烦。
采用方式二,只需配置好一次spring-mvc就OK。
方式二、
直接将org.springframework.http.converter.StringHttpMessageConverter 里面的属性defaultCharset设置成utf-8
如下设置
在spring-mvc.xml 中
<!-- ========================================分隔线========================================= -->
<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题 -->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<ref bean="stringHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
测试结果:
DEBUG 2019-05-25 19:08:30,872 org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor: Written [com.song.model.User@422c5b83账号:admin密码:8f61b106154bbc39cd8c2334c046bb62权限:2校验码:37A0session中的校验码:37A0] as "text/plain;charset=UTF-8" using [org.springframework.http.converter.StringHttpMessageConverter@74ab2d06]
写在最后
上述的配置已经过验证。在参考百度资料时,发现有很多文章采用的修改方案是在spring-mvc.xml 中进行如下配置
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter" >
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
<!-- application 可以在任意 form 表单里面 enctype 属性默认找到
<value>application/x-www-form-urlencoded</value>
-->
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
类似上述代码中的配置,我也使用过,但是发现并没有什么用,可能是我的SSM架构有问题,如果参考到本文的小伙伴在参考完解决方案后还是不行,可以测试下这个。