您的位置:首页 > 理论基础 > 计算机网络

关于Servlet中HttpServletRequest对象的setCharacterEncoding方法的讨论。

2014-01-26 13:53 453 查看
最近两天一直在关注编码这个问题,今天注意到了Servlet获得请求参数这个过程中涉及到的编码方式。

通过查看server配置文件的connector元素,发现,Servlet在处理请求参数时,使用的默认的编码时ISO-8859-1,这个不稀奇,毕竟是外国人写的嘛。

所以我们想要得到带中文的 参数 其中一种方法就是自行转换

如下:

String test = request.getParameter("test");
String test2 = new String(test.getBytes("iso-8859-1"),"utf-8");//注意,之所以后一个参数是utf-8编码,是因为我的java环境采用的默认编码方式时utf-8
System.out.println(test2);//这里可以打出正确的值

另外 我们注意到 request对象有个setCharacterEncoding,

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

方法解释中说要在读取请求参数前调用,看起来好像可以有设置参数编码的效果。

但是经过尝试后,发现不可以。

在查资料以后,发现这个设置方法其实是个老方法了,基本上是为了兼容过去版本的tomcat,

必须要在tomcat 的server配置文件中的 connector下声明 useBodyEncodingForURI=“true” 这个属性才有用。

useBodyEncodingForURI
This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is
false
.

在server配置文件 connector元素下 设置了该属性以后

在Servlet中就可以设置URL编码形式了

request.setCharacterEncoding("utf-8");
String test = request.getParameter("test");
System.out.println(test);

当然 还有另外一种方法

就是在connector元素下配置 URIEncoding来设置URL编码格式,如果不设置默认就是ISO-8859-1。

参考
http://tomcat.apache.org/tomcat-5.5-doc/config/http.html http://stackoverflow.com/questions/3029401/java-servlet-and-utf-8-problem
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: