DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
HTML 超鏈接中傳遞中文參數的亂碼問題分析與解決
編輯:HTML和Xhtml     

在 Vm 頁面中,一個超鏈接的 URL 需要拼接中文作為 GET 請求的參數。如果直接拼接,傳到後台 Action 的參數對象中取出來會是亂碼,必須先編碼再拼到 URL 上。

解決方法是在 Action 中添加一個成員變量,保存編碼後的中文參數,在 vm 頁面渲染時取出這個變量值,再拼接超鏈接。

過程中碰到的關鍵問題

調用 java.net.URLEncoder 的 encode() 方法時,如果沒有顯式指定字符集參數,URLEncoder 會使用默認字符集。而這個默認字符集在 Eclipse 裡跑 main() 方法和在 Tomcat 裡跑 Web 應用時得到的結果並不一樣,從而影響了編碼結果——這正是「本地測試正常、部署後卻亂碼」的典型根源。

相關源碼如下:

/**
* Translates a string into <code>x-www-form-urlencoded</code>
* format. This method uses the platform's default encoding
* as the encoding scheme to obtain the bytes for unsafe characters.
*
* @param s <code>String</code> to be translated.
* @deprecated The resulting string may vary depending on the platform's
* default encoding. Instead, use the encode(String,String)
* method to specify the encoding.
* @return the translated <code>String</code>.
*/
@Deprecated
public static String encode(String s) {
String str = null;
try {
str = encode(s, dfltEncName);
} catch(UnsupportedEncodingException e) {
// The system should always have the platform default
}
return str;
}

方法的註釋中也說明了不建議使用的原因:這個 encode(String) 方法依賴於平台字符集。因此正確做法始終是調用 encode(String, String) 並顯式傳入「UTF-8」,讓編碼行為在任何環境下都保持確定,從根本上杜絕亂碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved