您的位置:首页 > 其它

strut2提交form表单乱码

2015-04-18 15:58 127 查看
转其他人的

下面的我的jsp页面:

[html] view plaincopyprint?
1. <form action="indexAction.action">

2. <input name="dimName" type="text" />
3. <br />

4. <input name="submit" type="submit" />
5. </form>

而传到indexAction的dimName参数却是一堆乱码,

我的struts.xml关于编码的有如下配置:

[html] view plaincopyprint?
1. <constant name="struts.i18n.encoding" value="UTF-8" />

首先我所有的网页统一用的是UTF-8。。。

正常来说是没问题的,但是我在indexAction中

[java] view plaincopyprint?
1. System.out.println(dimName);

打印出的结果却是一堆乱码,花了我好长时间,也许是我经验不足吧!后来才发现,我把上面的jsp页面改为:

[html] view plaincopyprint?
1. <form action="indexAction.action" method="post">

2. <input name="dimName" type="text" />
3. <br />

4. <input name="submit" type="submit" />
5. </form>

乱码竟然消失了!!!我无语啊,看来post和get的区别还在于乱码问题。

怎么解决呢???

小弟找了一个可行的方法:

如果的都是用的Post的话,一切都没有问题!什么都不用动。但是如果你是用的get,就去你的tomcat目录下的conf/server.xml中找到下面一段:

[html] view plaincopyprint?
1. <Connector port="8080" protocol="HTTP/1.1"

2. connectionTimeout="20000"
3. redirectPort="8443" URIEncoding="UTF-8"/>

本来的URLEncoding="UTF-8"是没有的,加上这一句话,就行了,下面是为什么这么做的原因:

<constant name="struts.i18n.encoding" value="UTF-8" />

表示把struts2设置为utf-8,相当于response.setCharacterEncoding("UTF-8"),对HTTP请求的数据进行编码,但是get请求的数据是直接在URL中,通过配置struts2配置为utf-8或CharacterEncodingFilter拦截器都不会对URL进行拦截并转换。对于很多人来说会觉得用 request.setCharacterEncoding("字符集")可以指定解码方式,其实是不可以的,当看了servlet的官方API说明有对此方法的解释:Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().可以看出对于get方法它是无能为力的。那么到底用什么编码方式解码数据的呢,这是tomcat的事情了,默认缺省用的是 iso-8859-1

所以出现了上面的配置方式。

当然了还的一种:

[java] view plaincopyprint?
1. new String(request.getParameter("name").getBytes("iso-8859-1"),"客户端指定的URL encode编码方式")

总之,对于post来说,乱码问题是很容易解决的,关键在于get,因为所有页面上的编码设置对于get方法是彻底无效的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: