How do I correctly decode unicode parameters passed to a servlet

You are nearly there. EncodeURIComponent correctly encodes to UTF-8, which is what you should always use in a URL today.

The problem is that the submitted query string is getting mutilated on the way into your server-side script, because getParameter() uses ISO-8559-1 instead of UTF-8. This stems from Ancient Times before the web settled on UTF-8 for URI/IRI, but it’s rather pathetic that the Servlet spec hasn’t been updated to match reality, or at least provide a reliable, supported option for it.

(There is request.setCharacterEncoding in Servlet 2.3, but it doesn’t affect query string parsing, and if a single parameter has been read before, possibly by some other framework element, it won’t work at all.)

So you need to futz around with container-specific methods to get proper UTF-8, often involving stuff in server.xml. This totally sucks for distributing web apps that should work anywhere. For Tomcat see https://cwiki.apache.org/confluence/display/TOMCAT/Character+Encoding and also What’s the difference between “URIEncoding” of Tomcat, Encoding Filter and request.setCharacterEncoding.

Leave a Comment