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);

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

猜你喜欢

转载自gjp014.iteye.com/blog/2352585