Spring 3.1 MVC - 使用@ResponseBody注释时出现字符编码错误

时间:2012-08-24 08:21:05

标签: spring servlets spring-mvc character-encoding response

使用 @ResponseBody 注释时,我遇到了字符编码问题。如果我使用 response.getWriter()。write()方法我没有问题,我看不到像ş,ö,ı等土耳其字符。(我只看到问题标记而不是

我正在使用 Spring的CharacterEncodingFilter UTF-8编码

如何解决此问题?我是否必须将所有 @ResponseBody 注释使用的方法更改为 response.getWriter()。write()

示例方法:

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

这是我的字符编码过滤器:

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

还向Tomcat添加了URIEncoding属性:

    <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 个答案:

答案 0 :(得分:2)

不幸的是,使用@ResponseBody注释设置控制器中返回的字符串的编码并非易事,我认为您应该看到类似的问题:Who sets response content-type in Spring MVC (@ResponseBody)

在Spring 3.1配置中,您需要设置Rossen Stoyanchev answer 中显示的消息转换器。