日期:2014-05-18  浏览次数:20645 次

jsp 与javascript组合乱码
在JSP做一个项目的时候要用到JavaScript.JavaScript输出的表单提交数字,字符可以显示而中文就会出现乱码.上网找了好久就是解决不了.急急急!!!

下面是我做的一个示例.test_index.jsp显示一个提交按钮,点击按钮显示一个文本框和一个按钮然后点击按钮提交进入test.jsp显示中文乱码.各位大侠帮帮忙!!急!!
1.test_index.jsp
<%@   page   contentType= "text/html;   charset=gb2312 "   language= "java "   import= "java.sql.* "   errorPage= " "   %>
<SCRIPT   language= "JavaScript ">
function   Test()
{
document.write( " <table   cellspacing=0   cellpadding=0   align=center       valign=top   bgcolor=#BABAFA   border=0> ");
document.write( " <form   method=post   action=test.jsp> ");
document.write( " <tr   valign=top   align=left> <td   > ");
document.write( " <input   type=text   name=test_name   size=8> ");
document.write( " <input   type=submit   name=submit   value=提&nbsp;交> ");
document.write( " </td> </tr> </form> </table> ");
}
</SCRIPT>
<html>
<head>
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=gb2312 ">
<title> 无标题文档 </title>
</head>

<body>

<input   type= "submit "   name= "Submit "   value= "提交 "   onClick= "javascript:Test() ">
</body>
</html>


2.test.jsp

<%@   page   contentType= "text/html;   charset=gb2312 "   language= "java "   import= "java.sql.* "   errorPage= " "   %>
<html>
<head>
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=gb2312 ">
<title> 无标题文档 </title>
</head>

<body>
<%   String   test_name   =     new   String(request.getParameter( "test_name ").getBytes( "ISO-8859-1 "), "gb2312 ");
     
      out.print(test_name);
%>      

</body>
</html>

------解决方案--------------------
request.setCharacterEncoding( "UTF-8 ");
------解决方案--------------------
从这句 <%@ page contentType= "text/html; charset=gb2312 " language= "java " import= "java.sql.* " errorPage= " " %> 可以看出程序使用gb2312编码,所以转换时也应该转为gb2312编码,而不是UTF-8,要转UTF-8也得在页面也使用它的情况下。
所以你需要在页面中的 <%@ page contentType= "text/html; charset=gb2312 " language= "java " import= "java.sql.* " errorPage= " " %> 下面写个 <%request.setCharacterEncoding( "gb2312 ");%> ,不过它在TOMCAT 5下只对POST方法有效,GET方法还需要其他办法处理。
所以建议表单最好使用POST方法,你也可以考虑把request.setCharacterEncoding( "gb2312 ")写在filter里面