1. 程式人生 > >get提交時中文傳值亂碼的有關問題

get提交時中文傳值亂碼的有關問題

url=curWarnList.action?paramBean.bsIndex=1&paramBean.siteName=蕭山A基站,href連線提交其實是get提交方式,會造成中文亂碼。

這個主要是編碼方式不統一。JSP(手動設定)、Java(字串是unicode編碼)、作業系統、資料庫()、Tomcat等等,各種不同環境介質都有不同的編碼方式,如果編碼方式不統一,就會造成亂碼。

url引數中文是以ISO8859-1的編碼方式傳遞(url是通過web容器處理的,而tomcat預設的編碼方式ISO8859-1),struts的編碼方式是UTF-8,如果jsp頁面,myeclipse、web.xml中org.springframework.web.filter.CharacterEncodingFilter,都是UTF-8編碼,直接傳中文一般是不會亂碼的,如果再有亂碼。....

對於POST方式,表單中的引數值對是通過request body傳送給伺服器,此時瀏覽器會根據網頁的meta標籤中的content="text/html; charset=UTF-8"中指定的編碼進行對錶單中的資料進行編碼,然後發給伺服器,在伺服器端的程式中我們可以通過request.setCharacterEncoding("charset")方式(JSP程式碼) 設定編碼,然後通過request.getParameter獲得正確的資料。所以使用Post提交資料,編碼方式就是我們可以控制的了。Post表單的Html一般寫法如下:
<form action="test.jsp" method="post">


id:<input type="text" name="id"/>
name:<input type="text" name="name"/>
<input type="submit" value="傳送"/>
</form>

目前收集到4中方法,中文傳參documentPath為例:
1.改為form方式提交,不用超連結方式提交,用form方式傳參指定不亂碼。

2.使用Get方式提交資料,瀏覽器會對URL進行URL encode,然後傳送給伺服器,不同的瀏覽器可能會有不同的編碼方式,因此傳送之前需要使用JavaScript對引數進行統一編碼,比較麻煩,
通過

encodeURI(encodeURI(checkText))提交,java程式碼中用URLDecoder.decode解碼:

<script>
function download(documentPath){
var url = "<c:url value='/product/download.action?documentPath='/>"+documentPath;
url = encodeURI(encodeURI(url));
window.location.href=url;
}
</script>

java程式碼中取中文:
String documentPath = (String) request.getParameter('documentPath');
documentPath = URLDecoder.decode(documentPath,"utf-8");

問:為什麼要encodeURI(url)兩次才不會出現亂碼?

因為Tomcat伺服器會自動幫你做一次URLDecode,所以再加上你自己在程式碼裡面寫的URLDecode,一共就是兩個Decode了,既然要兩次Decode,當然就需要兩次Encode了。或許你會問,乾脆只Encode一次,然後在java程式碼裡不Decode,呵呵,這個也是不行的,這其實也就是為什麼要進行Encode的原因吧

3.修改tomcat的server.xml中的connector,新增URLEncoding="UTF-8"

4.中文從java中傳到jsp再通過url傳到java:
java中編碼:URLEncoder.encode(URLEncoder.encode("傳遞的中文","utf-8"));
java中解碼碼:URLDecoder.decode(request.getParameter('documentPath'),"utf-8");
或者
request.setCharacterEncoding("UTF-8"); //java程式碼中這樣設定一下,將請求編碼改為utf-8,但是隻對post方式有效
String path= request.getParameter("documentPath"); 
String method = request.getMethod(); //獲取提交方式 
if(method!=null && "GET".equals(method)){ //如果是get的方式的話 
path= new String(path.getBytes("ISO8859-1"), "UTF-8"); 
}

5.配置過濾器,但配置過濾器也一般適用於post提交

============

URLEncoder.encode(String s, String enc)
使用指定的編碼機制將字串轉換為 application/x-www-form-urlencoded 格式

URLDecoder.decode(String s, String enc) 
使用指定的編碼機制對 application/x-www-form-urlencoded 字串解碼。

傳送的時候使用URLEncoder.encode編碼,接收的時候使用URLDecoder.decode解碼,都按指定的編碼格式進行編碼、解碼,可以保證不會出現亂碼

===========