post亂碼:

原因:

​ 對於POST方式,它採用的編碼是由頁面來決定的即ContentType("text/html; charset=GBK")。當通過點選頁面的submit按鈕來提交表單時,瀏覽器首先會根據ContentType的charset編碼格式來對POST表單的引數進行編碼然後提交給伺服器,在伺服器端同樣也是用ContentType中設定的字符集來進行解碼,這就是通過POST表單提交的引數一般而言都不會出現亂碼問題。

當然這個字符集編碼我們是可以自己設定的:request.setCharacterEncoding(charset)設定編碼,然後通過request.getParameter獲得正確的資料。

  • 解決方案:

    springMVC已經提供了輪子給我們使用,在web.xml新增post亂碼filter

    在web.xml中加入:

    <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>
    
    <filter-mapping>
    
        <filter-name>CharacterEncodingFilter</filter-name>
    
        <url-pattern>/*</url-pattern>
    
    </filter-mapping>

get亂碼:

原因:

​ 對於GET方式,我們知道它的提交是將請求資料附加到URL後面作為引數,這樣依賴亂碼就會很容易出現,因為資料name和value很有可能就是傳遞的為非ASCII碼。

當URL拼接後,瀏覽器對其進行encode,然後傳送到伺服器。具體規則見URL編碼規則。

​ tomcat伺服器在進行解碼過程中URIEncoding就起到作用了。tomcat伺服器會根據設定的URIEncoding來進行解碼,如果沒有設定則會使用預設的ISO-8859-1來解碼。假如我們在頁面將編碼設定為UTF-8,而URIEncoding設定的不是或者沒有設定,那麼伺服器進行解碼時就會產生亂碼。

​ 這個時候我們一般可以通過new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8") 的形式來獲取正確資料,或者通過更改伺服器的編碼方式: tomcat 設定中<Connector port="8080"protocol="HTTP/1.1" maxThreads="150" connectionTimeout="20000"redirectPort="8443"URIEncoding="客戶端編碼"/> (預設是iso-8859-1)。

​ 伺服器獲取的資料都是ASCII範圍內的請求頭字元,其中請求URL裡面帶有引數資料,如果是中文或特殊字元,那麼encode後的%XY(編碼規則中的十六進位制數)通過request.setCharacterEncoding()是不管用的。這時候我們就能發現出現亂碼的根本原因就是客戶端一般是通過用UTF-8或GBK等對資料進行encode的,到了伺服器卻用iso-8859-1方式decoder。

  • 解決方案:

    1. 修改tomcat配置檔案新增編碼與工程編碼一致,如下:

      <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    2. 對引數進行重新編碼:

      //ISO8859-1是tomcat預設編碼,需要將tomcat編碼後的內容按utf-8編碼
      String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8");