关于使用Ajax请求json数据,@RequestMapping返回中文乱码的几种解决办法

一、问题描述:

  使用ajax请求json数据的时候,无论如何返回的响应编码都是ISO-8859-1类型,因为统一都是utf-8编码,导致出现返回结果中文乱码情况。

 1   $.ajax({
 2            type:"post",
 3            url:"http://...",
 4            data:JSON.stringify(data),
 5            dataType:"json",
 6            contentType:"application/json;charset=utf-8",
 7            success:function(data){
 8               //
 9            },
10            error:function(data){
11                //
12            }
13        })

  返回结果类型: 

  

二、原因:

  使用了SpringMVC框架的@RequestBody 和 @ResponseBody两个注解,分别完成请求对象到对象响应的过程,一步到位,但是因为Spring3.x以后有了HttpMessageConverter消息转换器,把返回String类型的数据编码全部默认转换成iso-8859-1的编码格式,所以就出现了我们遇到的乱码的情况,如返回list或其它则使用 MappingJacksonHttpMessageConverter。

  

三、解决办法:

  根据遇到的问题总结了三种可行的方案:

  1.手动设置响应的的Content-type属性:

1 @RequestMapping(value = "/next_page.action",method = RequestMethod.POST,produces = {"text/html;charset=utf-8"})

  直接设置返回的属性,这样有个不好的地方是,每个方法都要写一次produces,比较麻烦。

  2.不使用@ResponseBody注解,直接通过response的方法返回数据

1 @RequestMapping(value = "/next_page.action",method = RequestMethod.POST)
2     public void getUsersByPage(@RequestBody JSONObject params,HttpSession session,HttpServletResponse response) throws IOException {
3       
4         int page = Integer.parseInt(params.get("page").toString())-1;
5         List<User> ulist = null;
6         //。。。。
7         response.setContentType("text/html;charset=UTF-8");//这些设置必须要放在getWriter的方法之前,
8         response.getWriter().print(JSON.toJSONString(ulist));
9     }

  注意:response.setContentType一定要放在getWriter方法之前,否则编码设置将无效,因为它决定了该返回结果该以什么编码输出到客户端浏览器。不能颠倒。

  3.使用注解方式修改默认响应编码设置:

 1 <!-- 注解驱动 -->
 2     <mvc:annotation-driven>
 3         <!-- 指定http返回编码格式,不然返回ajax请求json会出现中文乱码 -->
 4         <mvc:message-converters>
 5             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
 6                 <property name="supportedMediaTypes">
 7                     <list>
 8                         <value>text/html;charset=UTF-8</value>
 9                         <value>application/json;charset=UTF-8</value>
10                         <value>*/*;charset=UTF-8</value>
11                     </list>
12                 </property>
13             </bean>
14         </mvc:message-converters>
15     </mvc:annotation-driven>

  在spring-servlet.xml配置文件中加入此配置,将修改转换器的默认编码方式为utf-8;此种方式会比较好用,因为一次配置就不会再有相同编码问题了,一次配置完美解决。

  以上三个方法都可以完美解决此种乱码问题,但是还是第三种配置方式最佳。

====

原文地址:https://www.cnblogs.com/caijh/p/7804745.html