【问题标题】:How to handle special chars in parameter values?如何处理参数值中的特殊字符?
【发布时间】:2012-04-05 23:19:20
【问题描述】:

如果在 GET 参数中使用特殊字符(如 Æ、Ø og Å)调用我的 Java Servlet,我会遇到一些问题:http://localhost:8080/WebService/MyService?test=Øst。

我的doGet 中有此代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println(request.getParameterValues("test")[0]);
}

控制台打印的消息是:Ã?st

Web 服务应该能够处理这样的调用。如何正确编码参数值?

【问题讨论】:

    标签: java servlets encoding


    【解决方案1】:

    您可以在请求参数之前尝试以下代码:

    request.setCharacterEncoding("utf-8");
    

    【讨论】:

    • 这仅适用于 POST 请求。
    【解决方案2】:

    您应该对特殊字符进行百分比编码 (http://en.wikipedia.org/wiki/Percent-encoding)。在您上面的示例中,“斜线 O”(Ø)的 UTF-8 代码为 0xd8,因此您的 URL 可以正确写入:

    http://localhost:8080/WebService/MyService?test=%d8st.

    这应该会导致

    Øst.
    

    从上面的 servlet 代码打印到控制台。

    【讨论】:

    【解决方案3】:

    这需要在服务级别进行配置。不清楚您使用的是哪一个,所以我将仅举 Tomcat 和 Glassfish 的示例。

    Tomcat:将URIEncoding 属性添加到/conf/server.xml 中的<Connector> 元素:

    <Connector ... URIEncoding="UTF-8">
    

    Glassfish:将&lt;parameter-encoding&gt; 添加到/WEB-INF/glassfish-web.xml(或sun-web.xml 用于旧版本):

    <parameter-encoding default-charset="UTF-8" />
    

    另见:

    【讨论】:

    • 我正在使用 Eclipse IDE 的 Tomcat 服务器。 WebContent/WEB-INF/web.xml 文件不包含任何连接器元素。正常吗?
    • 我说的是/conf/server.xml,而不是/WEB-INF/web.xml。它位于Tomcat安装文件夹中。但是,如果您没有在 Eclipse 中完全接管 Tomcat(这是默认设置;另请参阅 stackoverflow.com/questions/2280064/…),那么您需要通过 Servers 项目中的 server.xml 来配置它。请注意,对于生产 Tomcat,这需要在其 /conf/server.xml 中进行配置。
    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 2010-11-19
    • 2017-04-29
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多