How to handle special chars in parameter values?

2020-02-15 07:01发布

问题:

I've some issues with my Java Servlet if it's called with special chars (like Æ, Ø og Å) in the GET-parameters: http://localhost:8080/WebService/MyService?test=Øst.

I than have this code in my doGet:

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

The messages printed in the console is: Ã?st.

The Web Service should be able to handle calls like this. How can I encode the parameter values in a proper way?

回答1:

This needs to be configured at servet level. It's not clear which one you're using, so I'll give examples for Tomcat and Glassfish only.

Tomcat: add URIEncoding attribute to <Connector> element in /conf/server.xml:

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

Glassfish: add <parameter-encoding> to /WEB-INF/glassfish-web.xml (or sun-web.xml for older versions):

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

See also:

  • Unicode - How to get the characters right? - JSP/Servlet request


回答2:

you should be percent encoding special characters (http://en.wikipedia.org/wiki/Percent-encoding). In your example above, the "slashed O" (Ø) has the UTF-8 code 0xd8, so your URL would properly be written:

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

Which should result in

Øst.

being printed to the console, from your servlet code above.



回答3:

You could try the following code before requesting parameters:

request.setCharacterEncoding("utf-8");