JSP中文乱码问题解决方法小结(代码级)
2009-04-14 17:18
741 查看
JSP中文乱码问题解决方法小结
2007年02月13日 星期二 21:17
2007年02月13日 星期二 21:17
在使用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、中文作为[b]参数传递乱码[/b] 当我们把一段中文字符作为参数传递个另一页面时,也会出现乱码情况,解决方法如下: 在参数传递时对参数编码,比如 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方法[b]传参乱码解决方法[/b] 如: 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中[b]url传中文参数时乱码要注意的地方:[/b] 例如下面这个方法: //增加类别函数 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 转载自http://blog.csdn.net/ln831015/archive/2007/09/03/1769819.aspx |
相关文章推荐
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结(转)
- JSP中文乱码问题解决方法小结
- 【转】 JSP中文乱码问题解决方法小结
- JSP中文乱码问题解决方法小结
- jsp获取JavaScript生成的中文cookie出现乱码问题解决方法
- JSP中文及传中文参数乱码解决方法小结
- JSP MySQL插入数据时出现中文乱码问题的解决方法
- JSP中文及传中文参数乱码解决方法小结
- JSP、AJax中文乱码问题解决,escape(), encodeURI(), encodeURIComponent(),js对参数连续两次调用 encodeURI(String) 方法
- JSP页面编码问题研究三(中文字符乱码问题的解决方法)
- jsp之间传参数接受中文有乱码问题解决方法
- 关于jsp页面中中文乱码问题的解决方法
- linux+tomcat struts 2 Jsp页面传值中文乱码问题解决方法