JSP中文及傳中文引數亂碼解決方法小結
1、JSP頁面亂碼
這種亂碼的原因是應為沒有在頁面裡指定使用的字符集編碼,解決方法:只要在頁面開始地方用下面程式碼指定字符集編碼即可,
2、資料庫亂碼
這種亂碼會使你插入資料庫的中文變成亂碼,或者讀出顯示時也是亂碼,解決方法如下:
在資料庫連線字串中加入編碼字符集
String Url="jdbc:mysql://localhost/digitgulf?user=root&password=root&useUnicode=true&characterEncoding=GB2312";
並在頁面中使用如下程式碼:
response.setContentType
request.setCharacterEncoding("gb2312");
3、中文作為引數傳遞亂碼
當我們把一段中文字元作為引數傳遞個另一頁面時,也會出現亂碼情況,解決方法如下:
在引數傳遞時對引數編碼,比如
RearshRes.jsp?keywords=" + java.net.URLEncoder.encode(keywords)
然後在接收引數頁面使用如下語句接收
keywords=new String(request.getParameter("keywords").getBytes("8859_1"));
4、JSP頁面亂碼加這句
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="err.jsp" %>
5、在form中用get方法傳參亂碼解決方法
如:
1、 login.jsp
<%@ page language="java" contentType="text/html;charset=GBK"%>
<html>
<head>
<title>get傳參亂碼問題</title>
</head>
<body>
<form name="form1" action="login_do.jsp" method="GET">
<input type="text" name="username"/><br>
<input type="password" name="password"/><input type="submit" value="提交"/>
</form>
</body>
</html>
============
2、login_do.jsp
<%@ page language="java" contentType="text/html;charset=GBK"%>
<%
String temp=request.getParameter("username");
if(temp!=null){
temp=new String(temp.getBytes("8859_1"),"GBK");
}
out.println(temp);
%>
6、在ajax中url傳中文引數時亂碼要注意的地方:
例如下面這個方法:
//增加類別函式
function addSort(){
var name = document.getElementById("name").value; //取得id為name的文字框的值(中文的)
if(name==""){
alert("類別名稱不能為空!");
document.getElementById("name").focus();
return false;
}
var url = "action=add&name="+name; //這個name是中文引數
createXMLHttpRequest();
XMLHttpReq.onreadystatechange = AddStateChange;
XMLHttpReq.open("POST","adminSort",true); //通過post方式傳送
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLHttpReq.send(url);
}
============
在servlet中獲取引數的時候:
//解決url中文引數亂碼的關鍵是這裡,因為post方法提交資料預設的字元編碼是utf-8,
//如果後臺是gb2312或其他編碼資料就會產生亂碼,所以這裡也要將請求引數設為utf-8
//儘管你的jsp頁面是contentType="text/html;charset=GBK"
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
當輸出返回資訊時:
response.setContentType("text/xml;charset=UTF-8");
//這裡有點怪,當設為GBK時,ie顯示不正常,firefox則正常,設為utf-8時,兩者都顯示正常