【SpringMVC】一次处理项目中文乱码的经历

一次处理项目中文乱码的经历

背景

今天把旧服务器上的项目转移到新服务器上,结果返回的json中的中文乱码了,以为很奇怪,由于新服务器和旧服务器都是TX云,也不会有太大区别呀,因而乎开始了为期半天的蛋疼之旅。html

项目使用的是SpringMVC+MySQL+Mybatis,因而从各个方面查看Bug到底躲在哪,如下是我搜集到的和使用到的方法:mysql

在web.xml中加入编码过滤器

修改web.xml,加入以下filter:web

<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文件,因此···浪费了好长时间!!!spring

想一想时间也浪费了,不如好好整理一下吧,也许对大家有用呢^_^sql

另外发现AnnotationMethodHandlerAdapter和MappingJacksonHttpMessageConverter都是已经deprecated的类,也许对应的技术也应该更新换代了。数据库

相关文章
相关标签/搜索