0
votes

I have been scratching my head over an encoding problem with a Tomcat web application built with Spring MVC 3.1.1.

The Problem

Form input field value bound by spring via Freemarker Spring macro gets decoded as ISO-8859-1 instead of UTF-8.

Current Configuration

I have configured freemarker to encode everything in UTF-8.

    <bean id="freemarkerConfig"
       class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
       <property name="templateLoaderPath" value="/WEB-INF/templates/" />
       <property name="freemarkerSettings">
          <props>
            <prop key="auto_import">spring.ftl as spring</prop>
            <prop key="url_escaping_charset">UTF-8</prop>
          </props>
       </property>
    </bean>

Here is my character encoding filter setup in the web.xml file.

<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>

HTML markup head tag contains:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

UTF-8 encoding works great for displaying data that comes back in my freemarker views, with the exception of data that is bound to form values such as the input below.

<form id="main-search-form" action="search" method="GET">
   <@spring.formInput 'searchForm.q' 'id="q" maxlength="2048" autocomplete="off" spellcheck="false"'/>
</form>

As far as I can tell, and after doing hours of reading on the internet, it seems like Spring defaults to ISO-8859-1 in most cases, but I have not found a bean to override to change the type of decoding for bound data. Even when the HTTP request is encoded in UTF-8 and the tomcat container's Connector node is set with URIEncode="UTF-8", Spring tries to decode with ISO-8859-1.

Any help would be appreciated.

2

2 Answers

1
votes

After banging my head on my desk for hours, I think I finally figured out what the problem was. My configurations above were all correct (including the Tomcat connecter property, URIEncode="UTF-8").

I made the mistake of assuming that it was Spring MVC that was handling the encoding of my GET requests via a form submit.

However, it was really just a problem with the form markup. I needed to specify that the form charset as UTF-8.

<form id="main-search-form" action="search" method="GET" accept-charset="UTF-8"> 
   ...
</form>

This, in combination with the above configurations, resolved my problem.

1
votes

I needed to specify

  <form ... accept-charset="UTF-8"> ...

to get my UTF-8 characters submitted to the back-end correctly.