Spring mvc 下Ajax獲取JSON對象問題 406錯誤


我在學習springmvc過程中(我的項目是配置的后綴是.html),從controller返回對象。

如果我不使用 mvc-annotation-driver,而是手動配置,AnnotationMethodHandlerAdapter,然后在配置MappingJackson2HttpMessageConverter轉換器,這樣是可以正常將對象返回成json的。

但是我使用mvc-annotation-deiver,讓spring幫我們注冊AnnotationMethodHandlerAdapter,然后在配置MappingJackson2HttpMessageConverter轉換器,這樣返回對象,就會出現406錯誤。試了很久都沒有找到解決辦法,后來在網上搜索了,發現很多答案並不是適用於我這種樣子的錯誤,后來找到下面的這個答案,發現真的有效,我將返回后綴.html改為了.shtml就正常了。

 

總結下:其實說簡單點,真正原因就是,如果配置后綴是.html ,springmvc默認會采用[text/html]編碼。所以,后綴使用別的后綴或者,不用后綴就可以了。

 

 

 

以下部分轉載自:http://blog.sina.com.cn/s/blog_6316d5610102uy93.html 

 

Spring 3.2.x通過@ResponseBody標簽返回JSON數據的方法都報406錯: Failed to load resource: the server responded with a status of 406 (Not Acceptable) 以及報錯描述: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers () 
 

Spring 3.2 配置如下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
mediaTypes配置:
   
   
   
   
   
                 
        atom=application/atom+xml  
           html=text/html  
           json=application/json  
           *=*/*
       
       
   
 
用@ResponseBody返回對象出現問題,報406錯誤!!!
最后發現是:spring 3.2時requestedMediaTypes卻為[text/html]的情況報406錯誤,還有一個原因可能是由於采用的后綴有關,如果使用*.htm,*.html等,默認就會采用[text/html]編碼, 若把AJAX請求URL后面加上*.json,*.shtml等就OK
可參考:http://blog.csdn.net/gbtyy/article/details/17165605

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM