Spring 3.1 MVC - Getting character encoding error

2019-08-01 14:04发布

问题:

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:

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 .