1. 程式人生 > >springmvc框架解決中文亂碼

springmvc框架解決中文亂碼

使用servlet的配置和使用框架的設定

在使用servlet開發時,我們使用request設定編碼格式,一般在過濾器中設定。也就是設定傳送的格式和每次接受的資料都設定編碼個是為utf-8.

request.setCharacterEncording("utf-8");
response.setContentType("text/html;charset=utf-8");

在web.xml中配置過濾器,用來解決中文程式碼問題

 <filter>
        <filter-name>characterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

這樣解決的是普通的亂碼問題,當你前端返回的有json字串,處理請求返回的json字串的亂碼在springmvc-servlet.xml中配置以下程式碼,由於瀏覽器版本不同,配置資訊放的位置也不盡相同。低版本瀏覽器放在開啟註解掃描和定義掃描的包之間。高版本放在任意位置都可以解決。

  <!--開啟註解掃描功能-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 處理請求返回json字串的亂碼問題 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--定義掃描的包-->
    <context:component-scan base-package="com.qy.controller"></context:component-scan>

如果這樣還解決不了,就在上面的配置的檔案中加入fast-Json配置

<!-- 處理請求返回json字串的中文亂碼問題 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解決Controller返回json中文亂碼問題 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <!-- <property name="supportedMediaTypes" value="text/html;charset=UTF-8" /> -->
                <!-- <property name="supportedMediaTypes" value="application/json;charset=UTF-8" > -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>

<!--新加入的配置-->
            <!-- fastJson配置 -->
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>


        </mvc:message-converters>
    </mvc:annotation-driven>

總結

經過這樣的一番操作,一般都可以解決使用springmvc中文亂碼問題。