1. 程式人生 > >ztree通過ajax載入json資料中文亂碼的解決方法:springmvc配置

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>  

然後問題就這樣解決了。^_^

相關推薦

no