java中URL參數中有中文值,傳到服務端,在用request.getParameter()方法,得到的常常會是亂碼,這將涉及到字符解碼操作。
方法一:
http://xxx.do?ptname=’我是中國人’
在取URL傳遞中文的頁面對字符進行解碼:
String strPtname = request.getParameter("ptname");
strPtname = new String(strPtname.getBytes("ISO-885Array-1"), "UTF-8");
這種方式受具體應用環境限制,往往在應用部署環境發生改變時,還會出現中文亂碼。
方法二:
URLDecoder和URLEncoder,可以在任何應用部署環境下通用
URLDecoder和URLEncoder它的作用主要是用於普通字符串和application/x-www-form-rulencodedMIME字符串之間的轉換。
URLEncoder類包含一個encode(String s,Stringcharcter)靜態方法,它可以將普通字符串轉換成application/x-www-form-urlencodedMIME字符串
URLDecoder類包含一個decode(String s,Stringcharcter)靜態方法,它可以將看上去亂碼的特殊字符串轉換成普通字符串
編碼:URLEncoder(encode("包含中文的串"))
解碼:java.net.URLDecoder.decode("需要解碼的串","utf-8");
客戶端
title=encodeURI(encodeURI("包含中文的串"));
url="<%=request.getContextPath()%>/print/printList!printTable.action?title="+title;
在服務器端用java.net.URLDecoder.decode(getRequest().getParameter("title"),"UTF-8"),進行解碼。
URLDecoder和URLEncoder必須成對使用,報異常加try catch可解決。