zoukankan      html  css  js  c++  java
  • SSM框架:解决后台传数据到前台中文乱码问题,使用@ResponseBody返回json 中文乱码

    场景:

     在实际运用场景中,当前台发起请求后,我们需要从后台返回数据给前台,这时,如果返回的数据中包含中文,则经常会出现在后台查询出来都是好好,但是传输回去就莫名的乱码了,而且,我们明明已经在 web.xml 中进行编码过滤了,但还是乱码,让人很头疼。

    解决办法:

     第一种:这种方法,估计很多人都知道,那就在 controller 中的每个方法的  @RequestMappering 注解中进行编码设置,如下所示:

    @RequestMapping(value = "/queryUserById",produces = "text/plain;charset=utf-8")
    

       这种方法可以解决返回乱码问题,但是存在一个问题就是:需要在每一个的方法中都要写上 produces = "text/plain;charset=utf-8"

    这句设置,这样无形中,让我们的代码看起来,有那么一些不美观,作为一个慵懒的程序猿,也不会允许我们一直在重复做写这代码,

    所以有了第二种方法。

    第二种:与第一种方法相比,这种方法只需要在 spring-mvc.xml 配置文件中配置一次就好

    <!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题-->
        <mvc:annotation-driven >
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                    <property name = "supportedMediaTypes">
                        <list>
                            <value>application/json;charset=utf-8</value>
                            <value>text/html;charset=utf-8</value>
                            <!-- application 可以在任意 form 表单里面 enctype 属性默认找到 -->
                            <value>application/x-www-form-urlencoded</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    

      

  • 相关阅读:
    阿里云下Linux MySQL的安装
    protocol buffer相关
    Unity NGUI UIPanel下对粒子的剪裁
    NGUI中UILabel用省略号替换超出显示区域的内容
    Go交叉编译
    Unity3d使用未破解的TexturePacker
    编程之美 找出符合条件的整数
    算法导论~
    hadoop资料汇总(网上)
    SOE 中调用第三方dll
  • 原文地址:https://www.cnblogs.com/tanzq/p/8747861.html
Copyright © 2011-2022 走看看