SpringMVC 使用@ResponseBody返回json 中文乱码

来源:互联网 发布:c语言实验交换字母 编辑:程序博客网 时间:2024/05/01 04:50

这确实是个蛋疼的问题,Spring中解析字符串的转换器默认编码居然是ISO-8859-1

 

既然找到问题了,那就必须想办法改过来,不同版本的Spring好像方法还不一样,网上不少说的都是Spring3.*的,现在Spring4早都出来了

更改方式可以参考

http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody

http://www.cnblogs.com/chenying99/archive/2012/04/17/2453017.html

 

我现在用的Spring4.2.5,上面说的几个方法都试了,最后发现只有这两个可以

方法一,使用(produces = "application/json; charset=utf-8"):

    @RequestMapping(value="/getUsersByPage",produces = "application/json; charset=utf-8")//    @RequestMapping("/getUsersByPage")    @ResponseBody    public String getUsersByPage(String page,String rows,String text,HttpServletRequest request,HttpServletResponse response){

方法二,在spring-mvc.xml中添加:

复制代码
<!-- 处理请求返回json字符串的中文乱码问题 -->    <mvc:annotation-driven>        <mvc:message-converters>            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <property name="supportedMediaTypes">                    <list>                        <value>application/json;charset=UTF-8</value>                    </list>                </property>            </bean>        </mvc:message-converters>    </mvc:annotation-driven>
复制代码

以上两种方式经过验证都没有问题。

0 0
原创粉丝点击