Montag Jun 29, 2009

A trip to charset/encoding hell

I spent far too much time the last couple of days trying to solve an encoding problem in a springMVC/jquery based web application and here is a potential solution for those who run into the same or similar issues. I have a webapp that is mostly pure HTML but has some ajax comfort features in the backend. Everything worked for a long time and then the client started testing and immediately turned up a problem with text put into ajax forms turned into gibberish when containing Umlauts and such like. I started to investigate and went to hell. I quickly discovered that the same form when submitted via the jquery form plugin would screw up the text, whereas when submitted calssically without any javascript interference it would work. I thought that somewhere I must have forgotten to be explicit about the content-type or charset-encoding and made sue that each page would have the content-type header set to "text/html, charset=UTF-8". Now the ajax submitted form worked but the classical non-ajax submit would screw up the content. It seemed like there was also a difference between POSTing the form and submitting it via GET, with one generally working and the other not. I tried all sorts of combinations of headers and meta tags - alas no luck: I could have either one or the other. I searched the web and didn't find anything helpful for quite a while until I stumbled across this post, which basically introduced me to the Springs org.springframework.web.filter.CharacterEncodingFilter which can be used to enforce a charset header for every request. You just specify a filter like so:


<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
(in your web.xml).
I then also made sure that all my template based responses send a content-type header by setting
<property name="contentType" value="text/html;charset=UTF-8" />
for my view resolver.
Then I double-checked that the URIEncoding parameter of my tomcat connector is set to "UTF-8" and that my main layout template sends the
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/ />
header and now everything seems to work. I hope this might help somebody as desperate as I was.

Kommentare:

Senden Sie einen Kommentar:
  • HTML Syntax: Eingeschaltet