1.jsp頁面內容顯示亂碼
這種亂碼原因很簡單,一般的工具或解碼程序對中文字符解析時采用默認的解碼方式:
<%@ page contentType="text/html; charset=ISO-8859-1"%>
我們只需修改其編碼方式即可,如下:
<%@ page contentType="text/html; charset=UTF-8"%>
字符集:UTF-8 > GBK > GB2312
2.jsp 與 Servlet 間跳轉出現中文亂碼
2.1: method="Post"
jsp 中form 表單的 ation="XxxServlet",method="Post"時,提交表單后往往發現中文的屬性值在 Servlet 中獲取后變亂碼。
此時需要定位到 doPost() 方法,首先在方法內首行加上如下 code:
request.setCharacterEncoding("UTF-8");
意思是設置 request 的編碼為 "UTF-8",一般與 jsp 頁面一致
然后,再添加 code:
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
意思是設置 response 的編碼為 "UTF-8",即 Servlet 回傳 jsp 時的編碼,上面兩段用其一即可,保持一致是關鍵。
2.2:method="Get"
jsp 中form 表單的 ation="XxxServlet",method="Get"時,提交表單后往往發現中文的屬性值在 Servlet 中獲取后變亂碼。
此時需定位的 tomcat 的安裝目錄 %TOMCAT%/conf/server.xml 文件
尋找如下代碼片段:
1. <Connector port="8080" protocol="HTTP/1.1"
2. maxThreads="150"
3. connectionTimeout="20000"
4. redirectPort="8443"
5. URIEncoding="UTF-8"/>
手動加上URIEncoding="UTF-8"
3. javascript url 傳遞參數中文亂碼問題
方案一
html頁面:
function testOne() {
var url = "testTwo.action?expr="+你好;
window.location.href = encodeURI(url);
}
后台java代碼:
String expr = new String(
request.getParameter("expr").getBytes("ISO-8859-1"),"UTF-8");
方案二
html頁面:
function testTwo() {
var url = "testTwo.action?expr="+你好;
window.location.href= encodeURI(encodeURI(url));
}
后台java代碼:
String expr = java.net.URLDecoder.decode(lrequest.getParameter("expr") , "UTF-8");
如果用的是weblogic服務器的話,用方案二是可以解決的(我的weblogic的版本是weblogic 9.2的),方案一解決不了。
如果是tomcat服務器的話,這兩個方案都可以;也可以在傳遞參數不處理,后台用
String expr = new String(request.getParameter("expr").getBytes("ISO-8859-1"),"UTF-8");
也是可以的。
4. Java web下載文件文件名亂碼
第一種: 設置
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
這里將文件名編碼成UTF-8的格式,就不會出現URL出錯了。IE6下注意中文文字不能超過超過17個。
第二種:設置
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
將中文名編碼為ISO8859-1的方式。不過該編碼只支持簡體中文.
按照上訴方式,可以綜合一下兩種方式解決絕大部分中文問題。
fileName = URLEncoder.encode(fileNameSrc,"UTF-8");
if(fileName.length()>150)//解決IE 6.0 bug {
fileName=new String(fileNameSrc.getBytes("GBK"),"ISO-8859-1");
response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);
}