spring4 使用@ResponseBody 返回中文时发现客户端乱码

在使用spring4 使用@ResponseBody 返回中文时发现客户端乱码,奇怪了,已经在web.xml中配置了过滤器

配置如下:

 <filter>

        <description>字符集过滤器</description>

        <filter-name>encodingFilter</filter-name>

        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <init-param>

            <description>字符集编码</description>

            <param-name>encoding</param-name>

            <param-value>UTF-8</param-value>

            

            <param-name>forceEncoding</param-name>

            <param-value>true</param-value>

        </init-param>

    </filter>

    <filter-mapping>

        <filter-name>encodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

 

后来经过查资料发现 @RequestMapping 中添加 produces 配置 

配置如下

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

返回的中文不乱码了。

 

charset=UTF-8:设置字符集为utf-8

@RequestMapping(value = "/user/reg.do", produces = "application/xml"):表示将功能处理方法将生产xml格式的数据,此时根据请求头中的Accept进行匹配,如请求头“Accept:application/xml”时即可匹配。

 

此种方式相对使用@RequestMapping的“headers = "Accept=application/json"”更能表明你的目的。

 

当你有如下Accept头:

①Accept:text/html,application/xml,application/json

将按照如下顺序进行produces的匹配 ①text/html ②application/xml ③application/json

②Accept:application/xml;q=0.5,application/json;q=0.9,text/html

将按照如下顺序进行produces的匹配 ①text/html ②application/json ③application/xml

q参数为媒体类型的质量因子,越大则优先权越高(从0到1)

③Accept:*/*,text/*,text/html

将按照如下顺序进行produces的匹配 ①text/html ②text/* ③*/*

 

即匹配规则为:最明确的优先匹配。

 

 

2.当使用 response 返回json字符串时,中文又乱码了。

代码:

result = mapper.writeValueAsString(resReslt);

pt = response.getWriter();

 

pt.write(result);

 

修改代码后:

 

response.setHeader("Content-type", "text/html;charset=UTF-8");  

//这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859  

response.setCharacterEncoding("UTF-8");  

pt = response.getWriter();

 

pt.write(result);

 

设置报文头和字符集后,中文就不乱码了。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值