码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-04-05 15:51:02      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:write   style   res   lin   pos   targe   value   接收   extend   

   有时候我们发现接收的是中文,返回却是个?。这确实是个蛋疼的问题,Spring中解析字符串的转换器默认编码居然是ISO-8859-1

/**
 * Implementation of {@link HttpMessageConverter} that can read and write strings.
 *
 * <p>By default, this converter supports all media types ({@code &#42;&#47;&#42;}),
 * and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
 * by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("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中添加:(推荐这种)

    <!-- 设定消息转换的编码为utf-8防止controller返回中文乱码 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

 

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

 

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

标签:write   style   res   lin   pos   targe   value   接收   extend   

原文地址:https://www.cnblogs.com/qlqwjy/p/8722802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!