DIV CSS 佈局教程網

SpringMVC 中 Ajax 返回中文亂碼的幾種解決方法匯總
編輯:AJAX基礎知識     

用 SpringMVC 時,通過 JS 裡的 Ajax 發送請求並返回 JSON 數據,明明從數據庫拿出來的中文是正確的,展示到頁面上卻變成了亂碼。這個惱人的問題讓不少人抓破頭皮。本文彙總幾種切實可行的解決辦法(示例基於 spring-web-3.2.2)。

方法一:在 @RequestMapping 中指定 produces

加入 produces = "text/html;charset=UTF-8":

 @RequestMapping(value = "/configrole", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") public @ResponseBody String configrole() { ...... } 

方法二:修改 StringHttpMessageConverter 的默認字符集

根源在於 StringHttpMessageConverter 裡默認字符集是 ISO-8859-1,因此拿到源碼改成 UTF-8 後重新打包:

 public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); .......... }

方法三:修改 MediaType 構造方法並配置

 public MediaType(String type, String subtype, Charset charset) { super(type, subtype, charset); } 

並在 applicationContext-mvc.xml 加入配置:

 <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <bean class="org.springframework.http.MediaType"> <constructor-arg value="text" /> <constructor-arg value="plain" /> <constructor-arg value="UTF-8" /> </bean> </list> </property> </bean> 

方法四:通過 mvc:annotation-driven 配置消息轉換器

StringHttpMessageConverter 類負責處理請求或響應中的字符串,默認字符集為 ISO-8859-1,所以返回的 JSON 含中文時就會亂碼。它的父類有個 List<MediaType> supportedMediaTypes 屬性,用來存放需特殊處理的 MediaType;若需處理的類型不在列表中,就採用默認字符集。因此只需在配置文件中加入:

 <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>

如需處理其他 MediaType,可在 list 標簽中追加其他 value。以上就是 SpringMVC 中 Ajax 中文亂碼問題的幾種解法,希望對你有所幫助!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved