SpringMVC @RequestBody 自動轉json Http415錯誤


轉自: http://blog.csdn.net/tiantiandjava/article/details/46125141

 

項目中想用@RequestBody直接接收json串轉成對象

網上查了使用方法,看着非常簡單,不過經過測試很快發現頁面直接報415錯誤。

[html] view plain copy 在CODE上查看代碼片派生到我的代碼片
  1. <body>  
  2.         <h1>HTTP Status 415 - </h1>  
  3.         <HR size="1" noshade="noshade">  
  4.             <p>  
  5.                 <b>type</b> Status report  
  6.             </p>  
  7.             <p>  
  8.                 <b>message</b>  
  9.                 <u></u>  
  10.             </p>  
  11.             <p>  
  12.                 <b>description</b>  
  13.                 <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>  
  14.             </p>  
  15.          <HR size="1" noshade="noshade">  
  16.             <h3>Apache Tomcat/6.0.41</h3>  
  17. </body>  


經過一通查,多半的解決方法實說header里的 Content-Type 一定 application/json

但是問題依然沒有解決。

最后在《Spring in Action》里找到一個信息

有兩個前提條件:

The request’sContent-Typeheader must be set toapplication/json.
The JacksonJSONlibrary must be available on the application’s classpath. 

我滿足了第一個,所以在classpath中添加了一個jar。問題解決了。

[html] view plain copy 在CODE上查看代碼片派生到我的代碼片
  1.         <dependency>  
  2.             <groupId>com.fasterxml.jackson.core</groupId>  
  3.             <artifactId>jackson-databind</artifactId>  
  4.             <version>2.5.3</version>  
  5.         </dependency>  

所以如果大家遇到了同樣的問題,可以先排除一下這兩個因素。

------------------------------

還有一種情況,在以上兩個條件都滿足的情況下,還是報同樣的錯誤。

在springmvc的配置文件中必須有:

[html] view plain copy 在CODE上查看代碼片派生到我的代碼片
  1. <!-- 默認的注解映射的支持 -->  
  2. <mvc:annotation-driven />  


如果沒有這個配置也是會報這個錯的!

為什么會引入jackson-databind包呢,因為默認的配置會用到:

[java] view plain copy 在CODE上查看代碼片派生到我的代碼片
  1. com.fasterxml.jackson.databind.ObjectMapper  
        <mvc:message-converters>  
                    <bean  
                        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                        <property name="objectMapper">  
                            <bean class="com.fasterxml.jackson.databind.ObjectMapper">  
                                <property name="dateFormat">  
                                    <bean class="java.text.SimpleDateFormat">  
                                        <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
                                    </bean>  
                                </property>  
                            </bean>  
                        </property>  
                    </bean>  
                </mvc:message-converters>

 然后改過后,錯誤嘛又變成了400 description The request sent by the client was syntactically incorrect.

這是因為我傳入的json內容和我的接收這個請求的函數的參數不一致,不傳josn也會報這個錯


免責聲明!

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



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