Grails – UTF-8 Form Input Garbled when Running Within Tomcat

There are numerous articles describing charset problems when using Tomcat to run Grails applications that are supposed to accept UTF-8 characters (e.g. German umlauts äöüÄÖÜß). Most of them don’t mention a subtle cause that may jeopardize all your efforts to properly interpret UTF-8 form input. And fiddling around with Tomcat’s defaults was not an option for me, as the same Tomcat instance is to run other non-Grails legacy applications that rely on ISO-8859-1 being the default character set.

It took me some time to find out that Grails applications (1.2.0) behave just as expected under Tomcat (6.x) without any modification whatsoever, provided you don’t use Tomcat’s RequestDumperValve within your server.xml or context.xml.

<!-- Reiner: If you include this in your context.xml or server.xml,
     form input will always be interpreted as ISO-8859-1 :-(
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->

The reason for RequestDumperValve to garble form input is that it causes POST-parameters to be evaluated (using default ISO-8859-1) before Grails request filters have had a chance to set the request encoding to UTF-8. This behaviour is documented and RequestDumperValve is now deprecated due to its side effects.

The ultimate cause to this problem is that most browsers do not bother to state the character set that has been used to encode POST-parameters, thus leaving it up to the server to guess. Grails does this out-of-the-box within its applicationContext.xml:

<bean id="characterEncodingFilter"
      class="org.springframework.web.filter.CharacterEncodingFilter">
      <property name="encoding">
        <value>utf-8</value>
      </property>
</bean>

Credits: Ales at Grails User forum.

About Reiner

Born 1954 in Ratisbon (Bavaria, Germany), in 1976 punched cards at Berlin Technical University, caught hacking one of its mainframes by Horst Zuse (son of Konrad Zuse), started studying computer science and soon was offered a job whithin their computer department doing systems programming for IBM VM/370. While studying, jobbed around Germany at various places doing all sorts of things, then returned to Berlin to work at SRZ (computer aided typesetting). Never finished my master degree, but chose to take up self-employed work (which didn't turn me rich nor famous). Now working for a mid-sized software company within a very promising department as head of server software development.
This entry was posted in Grails. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s