servlets - request.getQueryString() 似乎需要一些编码

标签 servlets utf-8 character-encoding query-string

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

http://localhost:8080/servlet?param=value

当我在 servlet 中检索 URL 时,我对 UTF-8 字符有一些问题。
我使用这个代码:
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);
        ...

所以,如果我调用这个网址:
http://localhost:8080/servlet?param=così

结果是这样的:
Request: http://localhost:8080/servlet?param=cos%C3%AC

我该怎么做才能正确设置字符编码?

最佳答案

我以前遇到过同样的问题。不确定您使用的是什么 Java servlet 容器,但至少在 Tomcat 5.x(不确定 6.x)中是 request.setCharacterEncoding()方法实际上对 GET 参数没有影响。到您的 servlet 运行时,Tomcat 已经解码了 GET 参数,因此 setCharacterEncoding不会做任何事情。

解决这个问题的两种方法:

  • 将连接器的 URIEncoding 设置更改为 UTF-8。见 http://tomcat.apache.org/tomcat-5.5-doc/config/http.html .
  • 正如 BalusC 建议的那样,您自己解码查询字符串,然后自己手动将其解析(而不是使用 ServletRequest API)到参数映射中。

  • 希望这可以帮助!

    关于servlets - request.getQueryString() 似乎需要一些编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029401/

    相关文章:

    java - 如何使用 Apache Common fileupload 将上传文件的路径设置为 "context path"?

    xml - 为什么外籍人士拒绝破折号字符无效?

    python - unicode字节序让我困惑

    java - 内存 session 复制中的 Tomcat

    java - 在 Eclipse 中从 .jsp 文件访问 .java 文件

    Perl UTF8 连接问题

    php - Wordpress DB 字符集从 utf8mb4 更改为 utf8 导致错误

    java - 具有非 UTF-8 字符集的 JAR 文件

    postgresql - PostgreSQL-错误 : invalid byte sequence for encoding "UTF8": 0xeb 0x6e 0x74

    java - 自定义jsp标签未调用