SpringMvc全站中文亂碼處理(響應與請求中文亂碼處理)

一、請求亂碼處理

【1】在web.xml中處理

這種方式適用於Post中文亂碼處理。在web.xml中配置過濾器,這是Springmvc爲我們寫好的類,可以,通過指定編碼格式,從而有效控制Post請求亂碼,但是處理不了Get請求方式的亂碼

 <filter>
      <filter-name>characterEncodingFilter</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>

【2】在Tomcat服務器的配置文件上處理

~\apache-tomcat-7.0.90\conf\server.xml中處理

打開server.xml,大約在65行左右的位置

 <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

在Connector中加上URIEncoding="UTF-8"

 <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

此種方式可以處理,Get與Post請求方式的亂碼。配完之後,便不需要在考慮中文亂碼的問題

二、響應亂碼處理

【1】方式一,在@RequestMapping中加上,produces="text/html;charset=utf-8"

    @ResponseBody
    @RequestMapping(value="/test01.action",produces="text/html;charset=utf-8")
    public String test03() throws Exception {
        return "我愛你中國";
    }

通過,此種方式設置響應編碼格式爲utf-8。但是,此種方式,意味着,如果需要向頁面返回中文,則就需要書寫,過於麻煩。所以,請看第二種方式。

【2】方式二、在Springmvc.xml配置文件中書寫

<mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 處理響應中文內容亂碼 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8" />
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>  

將上述配置,放入到Springmvc,xml配置文件中,便可以對相應亂碼進行全站處理。

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章