黑马程序员技术交流社区
标题:
JSP页面显示乱码??
[打印本页]
作者:
曹思敏
时间:
2013-6-9 09:28
标题:
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>
作者:
杨增坤
时间:
2013-6-13 23:55
<%
request.setCharacterEncoding("utf-8");//设置接受方式编码方式
response.setCharacterEncoding("utf-8");//设置传递参数编码
%>加上这两句话,
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2