Spring MVC 使用@ResponseBody注解返回中文字符串乱码问题

在项目中碰到过Spring MVC 使用@ResponseBody注解返回的字符串中包含中文字符串乱码问题。
主要是Spring mvc解析返回的字符串中找到匹配的.StringHttpMessageConverter类解析该字符串,默认使用
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解决方案:
1、对于需要返回字符串的方法添加produces = "application/json; charset=utf-8"。针对的是单个方法
如:
 @RequestMapping(value = "/getInfos", produces="application/json;charset=UTF-8")
 @ResponseBody
 public String getInfos(@RequestBody String request) {
      return "中文";
    }

2、在spring mvc的配置文件中配置拦截器
<mvc:annotation-driven>  
    <mvc:message-converters register-defaults="true">  
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
            <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />  
        </bean>  
    </mvc:message-converters>  
</mvc:annotation-driven> 

猜你喜欢

转载自xu-nuo.iteye.com/blog/2393158