SSM框架:解决后台传数据到前台中文乱码问题,使用@ResponseBody返回json 中文乱码

场景:html

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

解决办法:spring

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

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

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

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

因此有了第二种方法。app

第二种:与第一种方法相比,这种方法只须要在 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>
相关文章
相关标签/搜索