Spring mvc 使用ajax 請求返回中文亂碼

controlller 代碼:

    @RequestMapping(value = "/user/getUsers.do", method = RequestMethod.GET)
    @ResponseBody
    public String getUsers() {
        return userService.getUserList();
    }

js 代碼:

$.ajax({
        type:'GET',
        url:'/user/getUsers.do',
        scriptCharset: 'utf-8',
        success: function (response) {
                alert(resoponse);
        }
});

在網(wǎng)上找了很久,也嘗試修改了 tomcat 工程里的 server.xml 文件也無濟于事,最后找到原因和解決辦法。

原因:

spring MVC有一系列HttpMessageConverter去處理用@ResponseBody注解的返回值,如返回list或其它則使用 MappingJacksonHttpMessageConverter,返回string,則使用 StringHttpMessageConverter,而這個convert使用的是字符集是iso-8859-1,而且是final的。所以在當返回json中有中文時會出現(xiàn)亂碼。

解決方法:

方法一:在配置文件中的mvc:annotation-driven中添加如下代碼:
  <mvc:annotation-driven >  
    <!-- 消息轉(zhuǎn)換器 -->  
    <mvc:message-converters register-defaults="true">  
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
        <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>  
      </bean>  
    </mvc:message-converters>  
  </mvc:annotation-driven> 
方法二:在 RequestMapping 中加入 produces:
@RequestMapping(value = "***",produces={"text/html;charset=UTF-8;","application/json;"})  

參考文章:https://www.cnblogs.com/HDK2016/p/7257177.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容