如何处理参数值中的特殊字符?

时间:2012-03-21 12:28:59

标签: java servlets encoding

如果在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 Service应该能够处理这样的调用。如何以正确的方式编码参数值?

3 个答案:

答案 0 :(得分:2)

这需要在服务级别配置。目前还不清楚你正在使用哪一个,所以我只给出Tomcat和Glassfish的例子。

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

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

Glassfish :将<parameter-encoding>添加到/WEB-INF/glassfish-web.xml(或旧版本sun-web.xml):

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

另见:

答案 1 :(得分:1)

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

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

哪个应该导致

Øst.

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

答案 2 :(得分:-1)

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

request.setCharacterEncoding("utf-8");