1. 程式人生 > >URL/ajax帶中文引數,後臺獲取亂碼

URL/ajax帶中文引數,後臺獲取亂碼

URL帶中文引數,後臺獲取亂碼

情況:做分頁時,需要帶中文引數跳轉頁面,程式碼放本地測試沒問題,可放到伺服器上,點選下一頁時就會出現空白,中文引數變成亂碼


原因:為防止亂碼,本地更改了tomcat\conf\server.xml檔案,指定瀏覽器的編碼格式為“簡體中文”,可是伺服器上並沒有更改,所以造成本地沒事,放到伺服器上就會出現亂碼。

解決方式
第一種:更改伺服器上tomcat\conf\server.xml檔案。--適合整個專案

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
改成
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"
/>
第二種:對URL進行轉碼,後臺解碼
jsp頁面:
<a id="pageUrl" href="jumpPage.action?name=${pro.name}">跳轉頁面</a>
<script type="text/javascript">
    $("pageUrl").click(function(){
        var url = $("#pageUrl").attr("href");
        url = encodeURI(encodeURI(url)); -- 轉碼兩次
        $("#pageUrl").attr("href",url);
    });
</script>

controller頁面:
String name = request.getParameter("name"); -- 系統自帶轉碼一次
name = java.net.URLDecode.decode(name, "utf-8"); -- 手動轉碼一次

用ajax時,中文引數亂碼

解決方法
漢字在前臺提交前用encodeURIComponent()函式編一下碼,在後臺用java.net.URLDecoder.decode(str,"utf-8")解碼。 -- 適合欄位少時
eg:
前臺
var name = $("[name='name']").val();
name = encodeURIComponent(name
);

後臺
String name = request.getParameter("name");
name = java.net.URLDecoder.decode(name,"utf-8");
encodeURI()與encodeURIComponent()區別
我的理解是,encodeURI()是對整個URL編碼,encodeURIComponent()是對URL的部分內容編碼,範圍不同。
http://www.cnblogs.com/shuiyi/p/5277233.html
http://www.cnblogs.com/tylerdonet/p/3483836.html