Spring 3.1 MVC-使用@ResponseBody批注时出现字符编码错误 [英] Spring 3.1 MVC - Getting character encoding error while using @ResponseBody annotation

查看:45
本文介绍了Spring 3.1 MVC-使用@ResponseBody批注时出现字符编码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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

How can I resolve this problem? Do I have to change all my @ResponseBody annotation used methods to 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"
/>

推荐答案

不幸的是,使用@ResponseBody批注为控制器中返回的字符串设置编码并不是一件容易的事,我认为您应该看到一个类似的问题:谁在Spring MVC(@ResponseBody)中设置响应内容类型

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)

在Spring 3.1配置中,您需要设置消息转换器,如 Rossen Stoyanchev答案所示.

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

这篇关于Spring 3.1 MVC-使用@ResponseBody批注时出现字符编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆