当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=慕容 测试