request.getQueryString() 似乎需要一些编码 [英] request.getQueryString() seems to need some encoding

查看:23
本文介绍了request.getQueryString() 似乎需要一些编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 UTF-8 有一些问题.我的客户端(在 GWT 中实现)向我的 servlet 发出请求,在 URL 中包含一些参数,如下所示:

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);
        ...

所以,如果我调用这个网址:

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 运行时,Tomcat 已经解码了 GET 参数,因此 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:

  1. 将连接器的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆