首页 > 开发 > JSP > 正文

动态网页制作技术JSP页面显示乱码问题的解决

2020-02-05 13:52:57
字体:
来源:转载
供稿:网友

  动态网页制作技术 jsp教程 网页页面乱码 解决jsp页面显示乱码问题。

用jsp开发网站过程中可能会有三种情况会产生乱码。

一、jsp页面显示乱码  二、表单提交中文时出现乱码  三、数据库连接时出现乱码

大家在jsp的开发过程中,经常出现中文乱码的问题,可能一至困扰着您,我现在把我在jsp开发中遇到的中文乱码的问题及解决办法写出来供大家参考。

一、jsp页面显示乱码

下面的显示页面(display.jsp)就出现乱码:

<html>
<head>
<title>jsp的中文处理CuoXin.com</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的中文处理CuoXin.com</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("jsp的中文处理");
%>
</body>
</html>

二、表单提交中文时出现乱码

下面是一个提交页面(submit.jsp),代码如下:

<html>
<head>
<title>jsp的中文处理CuoXin.com</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的中文处理CuoXin.com</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的中文处理CuoXin.com</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 string iso2gb(string qs)
{
try{
if (qs == null) return "null";
else
{
return new string(qs.getbytes("iso-8859-1"),"gb2312");
}
}
catch(exception e){
system.err.println("iso2gb error:"+e.getmessage());
}
return "null";
}
 
public string gb2iso(string qs)
{
try
{
if (qs == null) return "null";
else {
return new string(qs.getbytes("gb2312"),"iso-8859-1"); }
}
catch(exception e){ system.err.println("gb2iso error:"+e.getmessage());}
return "null";
}

字符存入数据库时用 gb2iso()函数,将字符从数据库取出时,再用 iso2gb()函数。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表