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

引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1

具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解决方法:

  • 需要返回字符串的方法添加注解,如下:
    @RequestMapping(value = "/doLogin",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String doLogin( User user){
        return userService.doLogin(user);
    }

  只能对单个方法有效。

  • 在配置文件中加入
<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> 

文章来源于:http://blog.csdn.net/gorch/article/details/50470598

原文地址:https://www.cnblogs.com/mylhy/p/8394535.html