ztree通过ajax加载json数据中文乱码的解决方法:springmvc配置

一、问题描述

使用zTree的异步刷新父级菜单时,服务器返回中文乱码,但项目中使用了SpringMvc,已经对中文乱码处理,为什么还会出现呢?

此处为的异步请求的配置:

Java代码  
  1. async: {  
  2.     enable: true,  
  3.     url: basePath + '/sysMenu/listSysMenu',  
  4.     autoParam: ["id=parentId"]  
  5. }  

 

SpringMvc中文字符处理:

Java代码  
  1. <mvc:annotation-driven>  
  2.     <mvc:message-converters>  
  3.     <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
  4.         <property name="supportedMediaTypes">  
  5.              <list>  
  6.                     <value>application/json;charset=UTF-8</value>  
  7.             <value>text/html;charset=UTF-8</value>  
  8.          </list>  
  9.         </property>  
  10.    </bean>  
  11.   </mvc:message-converters>  
  12. </mvc:annotation-driven>  

返回的结果有中文乱码:

Js代码  
  1. [  
  2.     {  
  3.         "menuId": "880095098165986816",  
  4.         "menuName": "????",  
  5.         "parentId": "880095098165986815",  
  6.         "menuUrl": "http://localhost:8080/imovie-manage/sysMenu/listSysMenuUI",  
  7.         "menuIcon": "",  
  8.         "menuSort": 1,  
  9.         "isEnable": 1,  
  10.         "parentMenuName": "??",  
  11.         "id": "880095098165986816",  
  12.         "name": "????",  
  13.         "pId": "880095098165986815"  
  14.     },  
  15.     {  
  16.         "menuId": "880095098165986817",  
  17.         "menuName": "???????",  
  18.         "parentId": "880095098165986815",  
  19.         "menuUrl": "http://localhost:8080/imovie-manage/sysMenu/treeSysMenuUI",  
  20.         "menuIcon": "",  
  21.         "menuSort": 1,  
  22.         "isEnable": 1,  
  23.         "parentMenuName": "??",  
  24.         "id": "880095098165986817",  
  25.         "name": "???????",  
  26.         "pId": "880095098165986815"  
  27.     }  
  28. ]  

 

二、解决方案

经过排查,发现是SpringMvc中文字符处理的supportedMediaTypes少了一种类型。

从浏览器发送的请求来看:



 

异步刷新使用的是post请求,但从服务器返回的时候,Content-Type为:text/plain;charset=ISO-8859-1

charset是ISO-8859-1,而不是UTF-8,而SpringMvc处理的中文乱码没有包含这种类型,所以导致中文乱码。

 

所以最后的解决方法是在SpringMvc中文处理加上text/plain这个类型,如下:

Java代码  
  1. <value>text/plain;charset=UTF-8</value>  

 具体如下:

Java代码  
  1. <property name="supportedMediaTypes">  
  2.     <list>  
  3.         <value>application/json;charset=UTF-8</value>  
  4.     <value>text/html;charset=UTF-8</value>  
  5.     <value>text/plain;charset=UTF-8</value>  
  6.     </list>  
  7. </property>  

然后问题就这样解决了。^_^

 

猜你喜欢

转载自blog.csdn.net/q669239799/article/details/78306708