問題場景:URL 裡的參數內容本身包含 & 符號,這會把參數截斷,導致後台接收出錯。下面提供前端與後端兩種處理思路。
復制代碼 代碼如下:
<a href="#" onclick="test('${group.type}','${group.cn }')">${group.cn }</a>
<script language="javascript">
function test(a,b){
alert("test");
location.href='groupsDetailServlet?groupTypeForDetail=' + a + '&cn=' + encodeURIComponent(b);
}
</script>
1. JSP:
復制代碼 代碼如下:
<a href="groupsDetailServlet?cn=${group.encodedCN }&groupTypeForDetail=${GroupType}">${group.cn }</a>
2. Java Bean(group):
復制代碼 代碼如下:
String cn; // 要顯示的 CN
String encodedCN; // 當參數傳的 CN
public Group(String cn) { this(); this.cn = cn; this.encodedCN = LdapUtil.encodeURLStr(cn); }
public void setCn (String name) { this.cn = name; setEncodedCN(LdapUtil.encodeURLStr(cn)); }
public String getCn () { return cn; }
public String getEncodedCN () { return encodedCN; }
public void setEncodedCN (String cn) { this.encodedCN = cn; }
3. 調用類裡解碼:
復制代碼 代碼如下:
String cn = LdapUtil.decodeURLStr(encodedCN);
4. LdapUtil.java:
復制代碼 代碼如下:
public static String encodeURLStr(String src)
{
return src != null && src.trim().length() > 0 ? src.replaceAll("&", "@") : "";
}
public static String decodeURLStr(String src)
{
return src != null && src.trim().length() > 0 ? src.replaceAll("@", "&") : "";
}
在用 URL 傳遞中文名或含特殊字符的參數時,後台處理常會出錯。若傳遞頁與接收頁字符集不一致(如一個 GB2312、一個 UTF-8),接收值就可能與原值不符。JavaScript 提供三個編碼函數:
escape():採用 ISO Latin 字符集編碼,把空格、標點、特殊及非 ASCII 字符轉成 %xx 格式(如空格為 %20)。不被編碼的字符:@ * / +。
encodeURI():把字符串以 UTF-8 格式轉成 escape 格式。不被編碼的字符:! @ # $& * ( ) = : / ; ? + '。
encodeURIComponent():同樣以 UTF-8 編碼,但比 encodeURI 編碼更多字符(如 /)。因此若字符串包含 URI 的各部分,不宜用它編碼,否則 / 被編碼後 URL 會出錯。不被編碼的字符:! * ( )。
實踐建議:
1. 傳遞參數時用 encodeURIComponent,可避免 # 等特殊字符截斷 URL。
2. 整體 URL 跳轉時用 encodeURI。
3. JS 內部使用數據時可用 escape。
此外,encodeURI/encodeURIComponent 是 JS 1.5 之後引入的,而 escape 從 1.0 就有了。對 0-255 以外的 Unicode 值,escape 會輸出 %u**** 格式,其他情況下三者結果相同。項目實踐中,直接對 URL 參數部分做 encodeURI(),後台 servlet 用 getParameter() 往往能直接拿到正確值(前提是參數未用到中文)。