各位高手,我建立一个表单,但在同一个页面返回所提取“名”的“值”的时候,如果是中文的话,返回的是乱码,原代码如下:
<%@page contentType="text/html;charset=GB2312"language="java"import="java.util.Enumeration" %>
<html>
<head>
<title>Value Of Name</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form name="form1" method="post" action="">
<!--定义表单数据-->
<input type="hidden" name="隐藏域" value="值">
<input type="text" name="文本域">
<input type="submit" name="Submit" value="提交按钮">
</form>
<p>
<%
//提取“名”集合
Enumeration names = request.getParameterNames();
String name,value;
for(Enumeration e=names;e.hasMoreElements();)
{
name = e.nextElement().toString();
value = request.getParameter(name);
out.println("<p>");
out.println(""+name+""+"的值是"+""+value+"");
out.println("</p>");
}
%>
</p>
</body>
</html>
value = request.getParameter(name).getBytes("ISO-8859-1"),"GBK");
package beans ;
public class ISOtoGB2312
{
public String getConvert(String str)
{
try
{
byte[] byteStr=str.getBytes("ISO-8859-1");
return new String(byteStr,"gb2312");
}
catch(Exception e)
{
return str;
}
}
}
这是一个经常遇到的问题,你可以写一个简单的javabean,以后在显示表单传递的中文数据时先转换一下!
调用方式:
<%@page contentType="text/html;charset=GB2312"language="java"import="java.util.Enumeration" %>
<jsp:useBean id="chage" scope="session" class="beans.ISOtoGB2312"/> //引用javabean
<html>
<head>
<title>Value Of Name</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form name="form1" method="post" action="">
<!--定义表单数据-->
<input type="hidden" name="隐藏域" value="值">
<input type="text" name="文本域">
<input type="submit" name="Submit" value="提交按钮">
</form>
<p>
<%
//提取“名”集合
Enumeration names = request.getParameterNames();
String name,value;
for(Enumeration e=names;e.hasMoreElements();)
{
name = chage.getConvert(e.nextElement().toString());//调用javaBean的getConvert方法
value = chage.getConvert(request.getParameter(name));
out.println("<p>");
out.println(""+name+""+"的值是"+""+value+"");
out.println("</p>");
}
%>
</p>
</body>
</html>
试试看!以后都可以使用这个JavaBean !
String s = new String(str.getBytes("ISO-8859-1"),"gb2312");
看一下这篇文章:http://www.clocksix.com/J2eeChinese
你定义一个METHOD
加个方法:
<%!public getStr(String str) throws Exception
{
String temp=str;
byte[] temp_p=temp.getBytes("ISO-8859-1");
return new String(temp_p,"GBK");;
}
%>
然后在插入数据库之前将有中文的变量用这个方法将变量转换一下:
String text=null;
if(request.getParameter("text")!=null&&request.getParameter("text")!="")
{
text=getStr(request.getParameter("text"));
}
在action.jsp中
<%
request.setCharacterEncoding("GBK");
%>
public static String funToChinese(String strvalue) {
try
{
if(strvalue==null)
{
return null;
}
else
{
strvalue = new String(strvalue.getBytes("ISO8859_1"),"GB2312");
return strvalue;
}
}
catch(Exception e)
{
return null;
}
}
在你的程序里加入这段代码,然后把你要引用的值通过funToChinaese()来转换试试看吧。应该没有问题的啦。