Spring返回json数据乱码问题

作者: 葉糖糖 | 来源:发表于2016-11-25 14:47 被阅读108次

使用spring框架是比较方便的,但是乱码总是让人心累。今天就和小伙伴们一起分享一下,本人在项目试验中遇到的乱码问题。

  • 使用注解方式属性(produces)解决乱码问题

这一种方式优点是比较快速,但是缺点就是,你需要重复的机械的敲打这样的代码。很是让哥哥捉急。

具体代码如下:

    /**
     * @author yetangtang
     * @date 2016/11/23
     * @param null
     * @return menuList4user
     */
    @ResponseBody
    @RequestMapping(value="/getMenuList.do", produces = "text/html;charset=UTF-8")
    public String getMenuList(){
        
        return "你好啊!";
    }
  • 使用xml文件配置解决乱码问题

个人认为这是一种一劳永逸的解决方式,因为我比较懒,所以我推荐使用这种解决方式。

具体代码如下:

    <!-- 处理请求时返回json字符串的中文乱码问题 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
  • 其它乱码解决方法

1、项目文件的编码方式不一致:建议采用一致的编码,个人喜欢默认使用UTF-8;
2、web容器的编码与项目文件编码一致:建议修改tomcat的配置文件,添加URIEncoding="UTF-8"。

具体代码如下:

 <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

相关文章

网友评论

    本文标题:Spring返回json数据乱码问题

    本文链接:https://www.haomeiwen.com/subject/lhiipttx.html