一次處理項目中文亂碼的經歷
背景
今天把舊服務器上的項目轉移到新服務器上,結果返回的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的類,也許對應的技術也應該更新換代了。