@ResponseBody导致的返回值中文乱码

新人学习springMVC开发框架,用到ajax 通过 @ResponseBody 来获取返回值。

不得不说 @ResponseBody的功能很强大,可以直接将返回类打包成json格式省却了很多事,

但是如果返回值是String类型的话,就会出现中文乱码问题,自己试着做了一些调整,并在网上查看了许多方法,在这里总结一下。


1.添加注解   produces = {"application/json;charset=UTF-8"}

@RequestMapping(value = "/method.do", produces = {"application/json;charset=UTF-8"})

适用于少量的,每写一个方法就得添加一次,不适合统一处理。

2.添加配置   在springMVC-*.xml里面进行String编码配置,如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
    <!-- utf-8编码 -->
    <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>
</beans>


如果可以看org.springframework.http.converter.StringHttpMessageConverter这个类的源码的话就会发现其默认的编码方式为  "ISO-8859-1",

这个应该是造成我们中文乱码的主要原因。


在这里不能不吐槽一下,好多老外写的jar包都会出现中文乱码问题,究其主要原因就是人家不用中文。。。故肯定会选择内存占用小的"ISO-8859-1",

啥时候才能大家都统一使用utf-8呀。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值