Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Spring MVC controller work with UTF-8?

I am using jQuery AJAX to submit a form to a Spring MVC controller in the backed. I am setting encoding on top of the jsp. In my request headers in Firebug I see -

Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive          115
Connection          keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest

However in my Spring MVC controller all the form values entered in Cyrillic turn into junk. And a twist to this is that this works fine in Safari but not in IE/FF/Chrome.

Any thoughts as to how I can set the correct encoding and prevent junk chars from getting submitted?

like image 510
Pushkar Avatar asked May 05 '11 10:05

Pushkar


1 Answers

I found the solution to this problem. I had set the encoding on top of each jsp page. Yet it was not working. So I added a spring character encoding filter in the web.xml. This will ensure that the encoding is correctly in the request.

<filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>
like image 163
Pushkar Avatar answered Sep 24 '22 19:09

Pushkar