2016-11-13 75 views
1

我試圖通過AJAX發送JSON對象到春天控制器,但收到一個錯誤415:發送JSON對象到彈簧柱控制器

"The server refused this request because the request entity is in a format not supported by the requested resource for the requested method."

我的春天控制器看起來像這樣和是在Tomcat 7運行 -

@RequestMapping(
    value = "/ab/greeting", 
    method=RequestMethod.POST, headers = "Accept=*/*", 
    produces = "application/json") 
public String greetingSubmit(@RequestBody Person p1) { 
    return "result"; 
} 

Person類的定義如下 -

package ab; 

public class Person { 

    String fname; 
    String lname; 
} 

,這裏是我的JavaScript進行調用 -

function getGreeting() { 
     $.ajax({ 
      url : "/ab/greeting", 
      contentType: "application/json", 
      type: 'POST', 
      async: false, 
      data: JSON.stringify({ fname: "John", lname: "Doe" }), 
      success: function (data) { 
      } 
     }); 
    } 

這裏是我的依賴在我的POM傑克遜相關的依賴 -

<dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-mapper-asl</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-core-asl</artifactId> 
     </dependency> 

諷刺的是,它工作時,我嘗試在春季啓動。

在Tomcat上,我也代替@RequestBody使用@ModelAttribute嘗試 - 在這種情況下,請求與error code 200返回,但P1對象出來空控制器。

這與Spring和Spring MVC之間的區別有關嗎? - 爲noob問題道歉。我的控制器類只能使用@Controller進行註釋。

我該如何修改這個以便能夠將AJAX對象從AJAX發送到Spring POST控制器?最後,我想發送一個5個對象的數組。

請幫忙。

感謝

+0

你能嘗試更換你的jQuery ajax開機自檢代碼的ContentType: 「應用/ JSON」, 數據:JSON.stringify({其中 「fname」 :「John」,「lname」:「Doe」}), cache:false, processData:false也嘗試在彈簧控制器@RequestMapping(value =「/ ab/greeting」, method = RequestMethod.POST) –

+0

也許是這個問題的重複重刑:http://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc – Crabime

+0

感謝您的答覆...我都試過但得到相同的結果如前 – lenniekid

回答

1

添加消耗屬性

@RequestMapping(value = "/ab/greeting", method=RequestMethod.POST,headers = "Accept=*/*",produces = "application/json", consumes="application/json") 
public String greetingSubmit(@RequestBody Person p1) { 
    return "result"; 
} 
+0

感謝您的回覆......我試過這個,但得到了和以前一樣的結果 – lenniekid

+0

@lenniekid你檢查過參數是否在發佈請求中正確發送?也許你可以嘗試將數據更改爲:data:{fname:「John」,lname:「Doe」} – cralfaro

+0

@lenniekid如果您沒有獲得足夠的信息以前的評論,請將下一個參數添加到您的方法中「 BindingResult結果「,那麼你將能夠提取更多關於這個問題的信息 – cralfaro

相關問題