天天看點

URL請求參數使用漢字,産生亂碼

         當jsp中設定了 <%@ page contentType="text/html;charset=utf-8" %>時,使用 http://localhost:8080/test7/hello.jsp?name=慕容    通路時,中文産生亂碼,你可能會很疑惑。但實際上呢,是因為請求參數預設使用 iso-8859-1 編碼傳遞,如果要正确顯示中文,應将請求參數編碼 轉換成gb2312或者utf-8。以下是個測試的例子。

hello.jsp

<%@ page contentType="text/html;charset=utf-8" %>
<%@ page errorPage="errorHandler.jsp" %>
<html>
<body>
<%
String name = request.getParameter("name");
if (name == null){
throw new RuntimeException("沒有指定 name 屬性。");
}
else{
	// 将字元串 name 的字元編碼轉換為漢字編碼
	name = new String(name.getBytes("iso-8859-1"), "utf-8");
}
%>
Hello, <%= name %>
</body>
</html>
           

errorHandler.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page isErrorPage="true" %>
<html>
<body>
請求不能被處理:<%=exception.getMessage()%><br>
請重試!
</body>
</html>
           

輸入 http://localhost:8080/test7/hello.jsp?name=慕容 測試