一次处理项目中文乱码的经历
背景
今天把旧服务器上的项目转移到新服务器上,结果返回的json中的中文乱码了,觉得很奇怪,因为新服务器和旧服务器都是TX云,也不会有太大区别呀,于是乎开始了为期半天的蛋疼之旅。
项目使用的是SpringMVC+MySQL+Mybatis,于是从各个方面查看Bug到底躲在哪,以下是我搜集到的和使用到的方法:
在web.xml中加入编码过滤器
修改web.xml,加入如下filter:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
连接数据库时加入字符编码
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
RequestMapping注解中加入produces字段
@RequestMapping(value = "/test", produces="application/json;charset=UTF-8")
SpringMVC配置文件spring-mvc.ml中加入消息转换器
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
SpringMVC配置文件spring-mvc.ml中加入StringHttpMessageConverter
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
The End
其实上面这些在项目中都已经使用了,最后我也是实在是找不到还有哪些没做的地方,于是开始怀疑是不是我数据库有问题,用了以前的数据库发现果然不乱码,一查数据库果然,数据本身存进去的时候就乱码了。因为是新开的机器,没有中文语言,我又在上面的MySQL执行了sql文件,所以···浪费了好长时间!!!
想想时间也浪费了,不如好好整理一下吧,也许对你们有用呢_
另外发现AnnotationMethodHandlerAdapter和MappingJacksonHttpMessageConverter都是已经deprecated的类,也许对应的技术也应该更新换代了。