大家在jsp的開發過程中,經常出現中文亂碼的問題,可能一至困擾著您,我現在把我在jsp開發中遇到的中文亂碼的問題及解決辦法寫出來供大家參考。
一、jsp頁面顯示亂碼
下面的顯示頁面(display.jsp)就出現亂碼:
<html>
<head>
<title>jsp的中文處理</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("jsp的中文處理");
%>
</body>
</html>
對不同的web服務器和不同的jdk版本,處理結果就不一樣。原因:服務器使用的編碼方式不同和瀏覽器對不同的字符顯示結果不同而導致的。解決辦法:在jsp頁面中指定編碼方式(gb2312),即在頁面的第一行加上:<%@ page contenttype="text/html; charset=gb2312"%>,就可以消除亂碼了。完整頁面如下:
<%@ page contenttype="text/html; charset=gb2312"%>
<html>
<head>
<title>jsp的中文處理</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("jsp的中文處理");
%>
</body>
</html>
二、表單提交中文時出現亂碼
下面是一個提交頁面(submit.jsp),代碼如下:
<html>
<head>
<title>jsp的中文處理</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<form name="form1" method="post" action="process.jsp">
<div align="center">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
下面是處理頁面(process.jsp)代碼:
<%@ page contenttype="text/html; charset=gb2312"%>
<html>
<head>
<title>jsp的中文處理</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getparameter("name")%>
</body>
</html>
如果submit.jsp提交英文字符能正確顯示,如果提交中文時就會出現亂碼。原因:瀏覽器默認使用utf-8編碼方式來發送請求,而utf-8和gb2312編碼方式表示字符時不一樣,這樣就出現了不能識別字符。解決辦法:通過request.secharacterencoding("gb2312")對請求進行統一編碼,就實現了中文的正常顯示。修改后的process.jsp代碼如下:
<%@ page contenttype="text/html; charset=gb2312"%>
<%
request.secharacterencoding("gb2312");
%>
<html>
<head>
<title>jsp的中文處理</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getparameter("name")%>
</body>
</html>
三、數據庫連接出現亂碼
只要涉及中文的地方全部是亂碼,解決辦法:在數據庫的數據庫url中加上useunicode=true&characterencoding=gbk就ok了。
四、數據庫的顯示亂碼
在mysql4.1.0中,varchar類型,text類型就會出現中文亂碼,對于varchar類型把它設為binary屬性就可以解決中文問題,對于text類型就要用一個編碼轉換類來處理,實現如下:
public class convert {
/** 把iso-8859-1碼轉換成gb2312
*/
public static string isotogb(string iso){
string gb;
try{
if(iso.equals("") || iso == null){
return "";
}
else{
iso = iso.trim();
gb = new string(iso.getbytes("iso-8859-1"),"gb2312");
return gb;
}
}
catch(exception e){
system.err.print("編碼轉換錯誤:"+e.getmessage());
return "";
}
}
}
把它編譯成class,就可以調用convert類的靜態方法isotogb()來轉換編碼。
商業源碼熱門下載www.html.org.cn
新聞熱點
疑難解答