2014-01-24 50 views
4

我做錯了什麼?我嘗試使用Spring mvc和JSON。當我嘗試調試我的代碼時,我正在查看該JavaScript的作品,但不起作用的控制器。在瀏覽器中,我收到錯誤415 Unsupported Media Type。JSON加彈簧mvc 3.2錯誤415(不支持的介質類型)

腳本:

$(document).ready(function() { 
    $('#newSmartphoneForm').submit(function(event) { 

     var producer = $('#producer').val(); 
     var model = $('#model').val(); 
     var price = $('#price').val(); 
     var json = { "producer" : producer, "model" : model, "price": price}; 

    $.ajax({ 
     url: $("#newSmartphoneForm").attr("action"), 
     data: JSON.stringify(json), 
     type: "POST", 

     beforeSend: function(xhr) { 
      xhr.setRequestHeader("Accept", "application/json"); 
      xhr.setRequestHeader("Content-Type", "application/json"); 
     }, 
     success: function(smartphone) { 
      var respContent = ""; 

      respContent += "<span class='success'>Smartphone was created: ["; 
      respContent += smartphone.producer + " : "; 
      respContent += smartphone.model + " : " ; 
      respContent += smartphone.price + "]</span>"; 

      $("#sPhoneFromResponse").html(respContent);   
     } 
    }); 

    event.preventDefault(); 
    }); 

}); 

控制器:

@RequestMapping(value="/create", method=RequestMethod.POST, 
     produces = MediaType.APPLICATION_JSON_VALUE, 
      consumes = MediaType.APPLICATION_JSON_VALUE) 
@ResponseBody 
public Smartphone createSmartphone(@RequestBody Smartphone smartphone) { 
    return smartphoneService.create(smartphone); 
} 
+0

您使用的是什麼Spring MVC版本?打開您的網絡控制檯。你看到正在發送的「Content-Type」頭文件嗎?向我們展示你的'智能手機'類。 –

回答

5

它可能會發生,因爲你沒有傑克遜在classpath在運行時。

錯誤消息表明服務器由於某種原因無法處理您的JSON請求。 JSON被轉換爲Java對象,其名稱爲消息轉換器。如果您的Spring XML配置中有<mvc:annotation-driven />(或者您啓用了Java Config),則JSON消息轉換器會自動註冊。如果你不這樣做,你必須註冊它。

+0

阿列克謝,你說得對。謝謝。我添加了,這有所幫助。但是有不同的種類(http://www.springframework.org/schema:cash,mvc,task)。我選擇了http://www.springframework.org/schema/mvc和所有的工作:) – user3233853

+0

作爲未來的搜索者的參考:如果'Content-Type'被設置爲'application,spring mvn會以相同的方式產生'415'/X WWW的形式-urlencoded'。設置爲'application/json',就像海報所做的那樣,是適當的方法。 – h7r

相關問題