1

I'm facing character encoding problem while using @ResponseBody annotation. If I use response.getWriter().write() method I have no problem which I can't see Turkish characters like ş,ö,ı, etc.. (I see just question mark instead of them)

I'm using Spring's CharacterEncodingFilter with UTF-8 encoding.

How can I resolve this problem? Do I have to change all my @ResponseBody annotation used methods to response.getWriter().write()?

Sample Method:

@RequestMapping(value = "/isScdValid.ajax")
    public @ResponseBody String isScdValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isValid = true; // for sample
        // continues...
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("isValid", isValid);
        if(isValid) {
            jsonObj.put("username", scd.getUsername());
            jsonObj.put("sessionUserId", scd.getUserId());

        }
    return jsonObj.toString(); // not encoding with UTF-8
//        response.getWriter().write(jsonObj.toString()); // works right
    }

Here's my character encoding filter:

<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-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Also added URIEncoding property to Tomcat:

    <Connector port="9090" protocol="HTTP/1.1" connectionTimeout="20000" 
redirectPort="9443"
URIEncoding="UTF-8" compression="on" 
compressableMimeType="text/html,text/xml,text/javascript,text/json,text/css,text/plain,application/javascript,application/json,application/pdf"
/>
1
  • Show us some code from your java method Commented Aug 24, 2012 at 8:28

1 Answer 1

2

Unfortunately, setting encoding for the strings returned in the controller with @ResponseBody annotation is not a trivial task, I think you should see a similar question: Who sets response content-type in Spring MVC (@ResponseBody)

In Spring 3.1 configuration, you need to set up message converter as it was shown in Rossen Stoyanchev answer .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.