日期:2014-05-16  浏览次数:20345 次

JSP中文及传中文参数乱码解决方法小结

JSP中文及传中文参数乱码解决方法小结

在使用JSP的过程中,最使人头疼的一个问题就是中文乱码问题,以下是我在软件开发中遇到的乱码问题以及解决方法。

  1、JSP页面乱码

  这种乱码的原因是应为没有在页面里指定使用的字符集编码,解决方法:只要在页面开始地方用下面代码指定字符集编码即可,

  2、数据库乱码

  这种乱码会使你插入数据库的中文变成乱码,或者读出显示时也是乱码,解决方法如下:
在数据库连接字符串中加入编码字符集
String Url="jdbc:mysql://localhost/digitgulf?user=root&password=root&useUnicode=true&characterEncoding=GB2312";
并在页面中使用如下代码:
response.setContentType("text/html;charset=gb2312");
request.setCharacterEncoding("gb2312");

  3、中文作为参数传递乱码

  当我们把一段中文字符作为参数传递个另一页面时,也会出现乱码情况,解决方法如下:
参数传递时对参数编码,比如
RearshRes.jsp?keywords=" + java.net.URLEncoder.encode(keywords)
然后在接收
参数页面使用如下语句接收
keywords=new String(request.getParameter("keywords").getBytes("8859_1"));

  4、JSP页面乱码加这句?

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="err.jsp" %>

???????5、在form中用get方法传参乱码解决方法

?????????? 如:

1、 login.jsp

<%@ page language="java" contentType="text/html;charset=GBK"%>
<html>
<head>
???? <title>get传参乱码问题</title>
</head>

<body>
???? <form name="form1" action="login_do.jsp" method="GET">
???? <input type="text" name="username"/><br>
???? <input type="password" name="password"/><input type="submit" value="提交"/>
???? </form>
</body>
</html>
============

2、login_do.jsp

<%@ page language="java" contentType="text/html;charset=GBK"%>

<%
????
???? String temp=request.getParameter("username");
???? if(temp!=null){
???????? temp=new String(temp.getBytes("8859_1"),"GBK");
???? }
???? out.println(temp);

%>

6、在ajax中url传中文参数时乱码要注意的地方:

例如下面这个方法:

//增加类别函数
function addSort(){
var name = document.getElementById("name").value;??????//取得id为name的文本框的值(中文的)
if(name==""){
?? alert("类别名称不能为空!");
?? document.getElementById("name").focus();
?? return false;
}
var url = "action=add&name="+name;???????????//这个name是中文参数
createXMLHttpRequest();
XMLHttpReq.onreadystatechange = AddStateChange;
XMLHttpReq.open("POST","adminSort",true);?????????//通过post方式传送
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLHttpReq.send(url);
}

============

在servlet中获取参数的时候:

//解决url中文参数乱码的关键是这里,因为post方法提交数据默认的字符编码是utf-8,
//如果后台是gb2312或其他编码数据就会产生乱码,所以这里也要将请求参数设为utf-8
//尽管你的jsp页面是contentType="text/html;charset=GBK"

request.setCharacterEncoding("UTF-8");??

String name = request.getParameter("name");

当输出返回信息时:

response.setContentType("text/xml;charset=UTF-8");

//这里有点怪,当设为GBK时,ie显示不正常,firefox则正常,设为utf-8时,两者都显示正常