JSP中文问题

1、JSP页面显示乱码2、表单提交中文时出现乱码3、数据库连
你们在JSP的开发过程当中,常常出现中文乱码的问题,可能一至困扰着您,我如今把我在JSP开发中遇到的中文乱码的问题及解决办法写出来供你们参考。
1、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>
2、表单提交中文时出现乱码
下面是一个提交页面(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.setCharacterEncoding("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>
3、数据库链接出现乱码
只要涉及中文的地方所有是乱码,解决办法:在数据库的数据库URL中加上useUnicode=true&characterEncoding=GBK就OK了。
4、数据库的显示乱码
在mysql4.1.0中,varchar类型,text类型就会出现中文乱码,对于varchar类型把它设为binary属性就能够解决中文问题,对于text类型就要用一个编码转换类来处理,实现以下:
public class Convert { 
/** 把ISO-8859-1码转换成GB2312
*/
public static String ISOtoGB(String iso){
String gb;
try{
if(iso.equals("") || iso == null){
return "";
}
else{
iso = iso.trim();
gb = new String(iso.getBytes("ISO-8859-1"),"GB2312");
return gb;
}
}
catch(Exception e){
System.err.print("编码转换错误:"+e.getMessage());
return "";
}
}
}
把它编译成class,就能够调用Convert类的静态方法ISOtoGB()来转换编码。