java中文亂碼解決之道(八)-----解決URL中文亂碼問題


我們主要通過兩種形式提交向服務器發送請求:URL、表單。而表單形式一般都不會出現亂碼問題,亂碼問題主要是在URL上面。通過前面幾篇博客的介紹我們知道URL向服務器發送請求編碼過程實在是實在太混亂了。不同的操作系統、不同的瀏覽器、不同的網頁字符集,將導致完全不同的編碼結果。如果程序員要把每一種結果都考慮進去,是不是太恐怖了?有沒有辦法,能夠保證客戶端只用一種編碼方法向服務器發出請求?

有!這里我主要提供以下幾種方法

一、javascript

使用javascript編碼不給瀏覽器插手的機會,編碼之后再向服務器發送請求,然后在服務器中解碼。在掌握該方法的時候,我們需要料及javascript編碼的三個方法:escape()、encodeURI()、encodeURIComponent()。

escape

采用SIO Latin字符集對指定的字符串進行編碼。所有非ASCII字符都會被編碼為%xx格式的字符串,其中xx表示該字符在字符集中所對應的16進制數字。例如,格式對應的編碼為%20。它對應的解碼方法為unescape()。

201501150002

事實上escape()不能直接用於URL編碼,它的真正作用是返回一個字符的Unicode編碼值。比如上面“我是cm”的結果為%u6211%u662Fcm,其中“我”對應的編碼為6211,“是”的編碼為662F,“cm”編碼為cm。

注意,escape()不對"+"編碼。但是我們知道,網頁在提交表單的時候,如果有空格,則會被轉化為+字符。服務器處理數據的時候,會把+號處理成空格。所以,使用的時候要小心。

encodeURI

對整個URL進行編碼,它采用的是UTF-8格式輸出編碼后的字符串。不過encodeURI除了ASCII編碼外對於一些特殊的字符也不會進行編碼如:! @ # $& * ( ) = : / ; ? + '。

201501150003

encodeURIComponent()

把URI字符串采用UTF-8編碼格式轉化成escape格式的字符串。相對於encodeURI,encodeURIComponent會更加強大,它會對那些在encodeURI()中不被編碼的符號(; / ? : @ & = + $ , #)統統會被編碼。但是encodeURIComponent只會對URL的組成部分進行個別編碼,而不用於對整個URL進行編碼。對應解碼函數方法decodeURIComponent。

當然我們一般都是使用encodeURI方來進行編碼操作。所謂的javascript兩次編碼后台兩次解碼就是使用該方法。javascript解決該問題有一次轉碼、兩次轉碼兩種解決方法。

一次轉碼

javascript轉碼:

var url = '<s:property value="webPath" />/ShowMoblieQRCode.servlet?name=我是cm';
window.location.href = encodeURI(url);

轉碼后的URL:http://127.0.0.1:8080/perbank/ShowMoblieQRCode.servlet?name=%E6%88%91%E6%98%AFcm

后台處理:

String name = request.getParameter("name");
        System.out.println("前台傳入參數:" + name);
        name  = new String(name.getBytes("ISO-8859-1"),"UTF-8");
        System.out.println("經過解碼后參數:" + name);

輸出結果:

前台傳入參數:??????cm
經過解碼后參數:我是cm

二次轉碼

javascript

var url = '<s:property value="webPath" />/ShowMoblieQRCode.servlet?name=我是cm';
window.location.href = encodeURI(encodeURI(url));

轉碼后的url:http://127.0.0.1:8080/perbank/ShowMoblieQRCode.servlet?name=%25E6%2588%2591%25E6%2598%25AFcm

后台處理:

        String name = request.getParameter("name");
        System.out.println("前台傳入參數:" + name);
        name  = URLDecoder.decode(name,"UTF-8");
        System.out.println("經過解碼后參數:" + name);

輸出結果:

前台傳入參數:E68891E698AFcm


經過解碼后參數:我是cm

filter

使用過濾器,過濾器LZ提供兩種,第一種設置編碼,第二種直接在過濾器中進行解碼操作。

過濾器1

該過濾器是直接設置request的編碼格式的。

public class CharacterEncoding implements Filter {
</span><span style="color: rgb(0,0,255)">private</span><span style="color: rgb(0,0,0)"> FilterConfig config ;
String encoding </span>= <span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">;

</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span><span style="color: rgb(0,0,0)"> destroy() {
    config </span>= <span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">;
}

</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span><span style="color: rgb(0,0,0)"> doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) </span><span style="color: rgb(0,0,255)">throws</span><span style="color: rgb(0,0,0)"> IOException, ServletException {
    request.setCharacterEncoding(encoding);
    chain.doFilter(request, response);
}

</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> init(FilterConfig config) <span style="color: rgb(0,0,255)">throws</span><span style="color: rgb(0,0,0)"> ServletException {
    </span><span style="color: rgb(0,0,255)">this</span>.config =<span style="color: rgb(0,0,0)"> config;
    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)">獲取配置參數</span>
    String str = config.getInitParameter(&quot;encoding&quot;<span style="color: rgb(0,0,0)">);
    </span><span style="color: rgb(0,0,255)">if</span>(str!=<span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">){
        encoding </span>=<span style="color: rgb(0,0,0)"> str;
    }
}

}

配置:

<!-- 中文過濾器的配置 -->
    <filter>
        <filter-name>chineseEncoding</filter-name>
        <filter-class>com.test.filter.CharacterEncoding</filter-class>
    <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">init-param</span><span style="color: rgb(0,0,255)">&gt;</span>
        <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">param-name</span><span style="color: rgb(0,0,255)">&gt;</span>encoding<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">param-name</span><span style="color: rgb(0,0,255)">&gt;</span>
        <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">param-value</span><span style="color: rgb(0,0,255)">&gt;</span>utf-8<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">param-value</span><span style="color: rgb(0,0,255)">&gt;</span>
    <span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">init-param</span><span style="color: rgb(0,0,255)">&gt;</span>
<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">filter</span><span style="color: rgb(0,0,255)">&gt;</span>

<span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">filter-mapping</span><span style="color: rgb(0,0,255)">&gt;</span>
    <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">filter-name</span><span style="color: rgb(0,0,255)">&gt;</span>chineseEncoding<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">filter-name</span><span style="color: rgb(0,0,255)">&gt;</span>
    <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">url-pattern</span><span style="color: rgb(0,0,255)">&gt;</span>/*<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">url-pattern</span><span style="color: rgb(0,0,255)">&gt;</span>
<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">filter-mapping</span><span style="color: rgb(0,0,255)">&gt;</span></pre>

過濾器2

該過濾器在處理方法中將參數直接進行解碼操作,然后將解碼后的參數重新設置到request的attribute中。

public class CharacterEncoding implements Filter {
    protected FilterConfig filterConfig ;
    String encoding = null;
</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span><span style="color: rgb(0,0,0)"> destroy() {
    </span><span style="color: rgb(0,0,255)">this</span>.filterConfig = <span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">;
}

</span><span style="color: rgb(0,128,0)">/**</span><span style="color: rgb(0,128,0)">
 * 初始化
 </span><span style="color: rgb(0,128,0)">*/</span>
<span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span><span style="color: rgb(0,0,0)"> init(FilterConfig filterConfig) {
    </span><span style="color: rgb(0,0,255)">this</span>.filterConfig =<span style="color: rgb(0,0,0)"> filterConfig;
}

</span><span style="color: rgb(0,128,0)">/**</span><span style="color: rgb(0,128,0)">
 * 將 inStr 轉為 UTF-8 的編碼形式
 * 
 * </span><span style="color: rgb(128,128,128)">@param</span><span style="color: rgb(0,128,0)"> inStr 輸入字符串
 * </span><span style="color: rgb(128,128,128)">@return</span><span style="color: rgb(0,128,0)"> UTF - 8 的編碼形式的字符串
 * </span><span style="color: rgb(128,128,128)">@throws</span><span style="color: rgb(0,128,0)"> UnsupportedEncodingException
 </span><span style="color: rgb(0,128,0)">*/</span>
<span style="color: rgb(0,0,255)">private</span> String toUTF(String inStr) <span style="color: rgb(0,0,255)">throws</span><span style="color: rgb(0,0,0)"> UnsupportedEncodingException {
    String outStr </span>= &quot;&quot;<span style="color: rgb(0,0,0)">;
    </span><span style="color: rgb(0,0,255)">if</span> (inStr != <span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">) {
        outStr </span>= <span style="color: rgb(0,0,255)">new</span> String(inStr.getBytes(&quot;iso-8859-1&quot;), &quot;UTF-8&quot;<span style="color: rgb(0,0,0)">);
    }
    </span><span style="color: rgb(0,0,255)">return</span><span style="color: rgb(0,0,0)"> outStr;
}

</span><span style="color: rgb(0,128,0)">/**</span><span style="color: rgb(0,128,0)">
 * 中文亂碼過濾處理
 </span><span style="color: rgb(0,128,0)">*/</span>
<span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span><span style="color: rgb(0,0,0)"> doFilter(ServletRequest servletRequest,
        ServletResponse servletResponse, FilterChain chain) </span><span style="color: rgb(0,0,255)">throws</span><span style="color: rgb(0,0,0)"> IOException,
        ServletException {
    HttpServletRequest request </span>=<span style="color: rgb(0,0,0)"> (HttpServletRequest) servletRequest;
    HttpServletResponse response </span>=<span style="color: rgb(0,0,0)"> (HttpServletResponse) servletResponse;

    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 獲得請求的方式 (1.post or 2.get), 根據不同請求方式進行不同處理</span>
    String method =<span style="color: rgb(0,0,0)"> request.getMethod();
    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 1. 以 post 方式提交的請求 , 直接設置編碼為 UTF-8</span>
    <span style="color: rgb(0,0,255)">if</span> (method.equalsIgnoreCase(&quot;post&quot;<span style="color: rgb(0,0,0)">)) {
        </span><span style="color: rgb(0,0,255)">try</span><span style="color: rgb(0,0,0)"> {
            request.setCharacterEncoding(</span>&quot;UTF-8&quot;<span style="color: rgb(0,0,0)">);
        } </span><span style="color: rgb(0,0,255)">catch</span><span style="color: rgb(0,0,0)"> (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 2. 以 get 方式提交的請求</span>
    <span style="color: rgb(0,0,255)">else</span><span style="color: rgb(0,0,0)"> {
        </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 取出客戶提交的參數集</span>
        Enumeration&lt;String&gt; paramNames =<span style="color: rgb(0,0,0)"> request.getParameterNames();
        </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 遍歷參數集取出每個參數的名稱及值</span>
        <span style="color: rgb(0,0,255)">while</span><span style="color: rgb(0,0,0)"> (paramNames.hasMoreElements()) {
            String name </span>= paramNames.nextElement(); <span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 取出參數名稱</span>
            String values[] = request.getParameterValues(name); <span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 根據參數名稱取出其值
            </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 如果參數值集不為空</span>
            <span style="color: rgb(0,0,255)">if</span> (values != <span style="color: rgb(0,0,255)">null</span><span style="color: rgb(0,0,0)">) {
                </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 遍歷參數值集</span>
                <span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 0; i &lt; values.length; i++<span style="color: rgb(0,0,0)">) {
                    </span><span style="color: rgb(0,0,255)">try</span><span style="color: rgb(0,0,0)"> {
                        </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 回圈依次將每個值調用 toUTF(values[i]) 方法轉換參數值的字元編碼</span>
                        String vlustr =<span style="color: rgb(0,0,0)"> toUTF(values[i]);
                        values[i] </span>=<span style="color: rgb(0,0,0)"> vlustr;
                    } </span><span style="color: rgb(0,0,255)">catch</span><span style="color: rgb(0,0,0)"> (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 將該值以屬性的形式藏在 request</span>

request.setAttribute(name, values);
}
}

    }
    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 設置響應方式和支持中文的字元集</span>
    response.setContentType(&quot;text/html;charset=UTF-8&quot;<span style="color: rgb(0,0,0)">);

    </span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)"> 繼續執行下一個 filter, 無一下個 filter 則執行請求</span>

chain.doFilter(request, response);
}
}

配置:

<!-- 中文過濾器的配置 -->
    <filter>
        <filter-name>chineseEncoding</filter-name>
        <filter-class>com.test.filter.CharacterEncoding</filter-class>
    </filter>
<span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">filter-mapping</span><span style="color: rgb(0,0,255)">&gt;</span>
    <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">filter-name</span><span style="color: rgb(0,0,255)">&gt;</span>chineseEncoding<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">filter-name</span><span style="color: rgb(0,0,255)">&gt;</span>
    <span style="color: rgb(0,0,255)">&lt;</span><span style="color: rgb(128,0,0)">url-pattern</span><span style="color: rgb(0,0,255)">&gt;</span>/*<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">url-pattern</span><span style="color: rgb(0,0,255)">&gt;</span>
<span style="color: rgb(0,0,255)">&lt;/</span><span style="color: rgb(128,0,0)">filter-mapping</span><span style="color: rgb(0,0,255)">&gt;</span></pre>

其他

1、設置pageEncoding、contentType

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>

2、設置tomcat的URIEncoding

在默認情況下,tomcat服務器使用的是ISO-8859-1編碼格式來編碼的,URIEncoding參數對get請求的URL進行編碼,所以我們只需要在tomcat的server.xml文件的<Connector>標簽中加上URIEncoding="utf-8"即可。


-----原文出自:http://cmsblogs.com/?p=1526,請尊重作者辛勤勞動成果,轉載說明出處.

-----個人站點:http://cmsblogs.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM