Wednesday, October 29, 2008

Special Characters in Spring MVC

You might be surprised to see when you type special characters on the form and in the controller, it comes in wrong e.g.
I typed a copy right sign, "©".  It came in as "©".
Even though I have already set my page's encoding to UTF-8, it didn't work.

The problem is Spring tried to encode using ISO-8859-1 still.  I think it is because, per Servlet standard, that is the default request/response encoding.

The solution is simple; we just have to explicitly set the encoding we want using CharacterEncodingFilter.  Thank to a post in Spring Forum.

Add the following to your web.xml.
<filter>
<filter-name>springCharacterEncodingFilter</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>springCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

No comments: