request.getQueryString()似乎需要一些编码 [英] request.getQueryString() seems to need some encoding
问题描述
我对UTF-8有一些问题。我的客户端(在GWT中实现)向URL中的一些参数请求我的servlet,如下所示:
I have some problem with UTF-8. My client (realized in GWT) make a request to my servlet, with some parametres in the URL, as follow:
http://localhost:8080/servlet?param=value
当在servlet中检索URL时,有一些UTF-8字符的问题。
我使用这个代码:
When in the servlet I retrieve the URL, I have some problem with UTF-8 characters. I use this code:
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String reqUrl = request.getRequestURL().toString();
String queryString = request.getQueryString();
System.out.println("Request: "+reqUrl + "?" + queryString);
...
所以,如果我调用这个url:
So, if I call this url:
http://localhost:8080/servlet?param=così
结果如下:
Request: http://localhost:8080/servlet?param=cos%C3%AC
如何正确设置字符编码?
What can I do to set up properly the character encoding?
推荐答案
之前我遇到过同样的问题。不确定你使用什么Java servlet容器,但至少在Tomcat 5.x(不确定6.x)中, request.setCharacterEncoding()
方法不会真的对GET参数有影响。到您的servlet运行时,GET参数已经被Tomcat解码,因此 setCharacterEncoding
将不会做任何事情。
I've run into this same problem before. Not sure what Java servlet container you're using, but at least in Tomcat 5.x (not sure about 6.x) the request.setCharacterEncoding()
method doesn't really have an effect on GET parameters. By the time your servlet runs, GET parameters have already been decoded by Tomcat, so setCharacterEncoding
won't do anything.
两种方法来解决此问题:
Two ways to get around this:
-
将连接器的URIEncoding设置更改为UTF-8。请参见 http://tomcat.apache.org/tomcat-5.5-doc /config/http.html 。
如BalusC建议,自行解码查询字符串,并手动解析它(与使用ServletRequest API)。
As BalusC suggests, decode the query string yourself, and manually parse it (as opposed to using the ServletRequest APIs) into a parameter map yourself.
希望这有助于!
这篇关于request.getQueryString()似乎需要一些编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!