温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springMVC @response 中文乱码解决

发布时间:2020-07-22 23:10:17 来源:网络 阅读:7523 作者:sxhjhf 栏目:软件技术

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

不得不说 @response的功能很强大,可以直接将返回类打包成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>
    <!-- <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven> -->
 。。。。。
</beans>

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

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


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

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI