从js向Action传中文参数出现乱码问题的解决方法
时间:2021-04-19 08:08:47|栏目:JavaScript代码|点击: 次
做项目的时候,发现Action获取jsp表单中的中文参数,只要整个项目都采用UTF-8编码格式都不会出现乱码问题;但JSP中用到JS,并从JS向Action传中文参数,就会出现中文乱的现象。几经询问百度,上面说法很多。
经过实践发现下面的方法可以解决中文乱码问题:
JSP的JS中:中文参数用encodeURI(encodeURI(中文参数)),经过两次转码。例如:
function show(next,id,realName){
document.forms['f2'].action="usersearchNextPage?next="+next+"&id="+id+"&realName="+encodeURI(encodeURI(realName));
document.forms['f2'].submit();
}
其中 realName是中文参数。故在提交的URL中将realName转码两次。encodeURI(encodeURI(realName))
Action中:接收中文参数时解码。用:java.net.URLDecoder.decode(realName,"UTF-8");
如:
String realName = ServletActionContext.getRequest().getParameter("realName");
try {
realName = java.net.URLDecoder.decode(realName,"UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
经过上述处理,问题解决。
经过实践发现下面的方法可以解决中文乱码问题:
JSP的JS中:中文参数用encodeURI(encodeURI(中文参数)),经过两次转码。例如:
复制代码 代码如下:
function show(next,id,realName){
document.forms['f2'].action="usersearchNextPage?next="+next+"&id="+id+"&realName="+encodeURI(encodeURI(realName));
document.forms['f2'].submit();
}
其中 realName是中文参数。故在提交的URL中将realName转码两次。encodeURI(encodeURI(realName))
Action中:接收中文参数时解码。用:java.net.URLDecoder.decode(realName,"UTF-8");
如:
复制代码 代码如下:
String realName = ServletActionContext.getRequest().getParameter("realName");
try {
realName = java.net.URLDecoder.decode(realName,"UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
经过上述处理,问题解决。
栏 目:JavaScript代码
下一篇:js实现倒计时秒杀效果
本文标题:从js向Action传中文参数出现乱码问题的解决方法
本文地址:http://www.codeinn.net/misctech/104543.html






