2016-02-13 74 views
1

我試圖從窗體發送JSON到一個spring mvc控制器,但我總是得到錯誤415.
我已經嘗試更改標頭,類型,stringify等正如其他帖子所說,沒有成功。
有人可以幫忙嗎?我是新手,仍然在努力理解。發送JSON到Spring MVC - 錯誤415

主要頁面功能:

<script type="text/javascript"> 
function ConvertFormToJSON(form) { 
    var array = jQuery(form).serializeArray(); 
    var json = {}; 

    jQuery.each(array, function() { 
     json[this.name] = this.value || ''; 
    }); 

    return json; 
} 

jQuery(document).ready(function() { 
    jQuery('#novoitem').submit(function() { 

     var form = this; 
     var json = ConvertFormToJSON(form); 
     console.log(JSON.stringify(json)); 
     jQuery.ajax({ 
      dataType : "json", 
      contentType : "application/json", 
      type : "POST", 
      url : "inventario/", 
      data : JSON.stringify(json), 
      contentType : "application/json", 
      success : function(data) { 
       alert(data); 
      } 
     }); 

     return false; 
    }); 
}); 

形式:

<form id="novoitem" method="post" enctype='application/json'> 
    <label for="usuario">Usuario:</label> 
    <input id="usuario" name="usuario" type="text"> 
    <label for="tipo">Tipo:</label> 
    <input id="tipo" name="tipo" type="text"> 
    <label for="nomeItem">Item:</label> 
    <input id="nomeItem" name="nomeItem" type="text"> 
    <label for="quantidade">Quantidade:</label> 
    <input id="quantidade" name="quantidade"type="text"> 
    <label for="vencimento">Vencimento:</label> 
    <input id="vencimento" name="vencimento" type="text"> 
    <input type="submit" value="Incluir"> 
</form> 

控制器:

@RequestMapping(value = "/inventario/", method = RequestMethod.POST) 
public ResponseEntity<Void> insereItem(@RequestBody Item item){...} 

CONSOLE.LOG字符串化:

{"usuario":"a","tipo":"b","nomeItem":"c","quantidade":"d","vencimento":"e"} 

錯誤:

POST http://localhost:8888/inventario/ 415 (Unsupported Media Type) 
+0

取代:URL:「inventario和@RequestMapping(值=‘/ inventario’,方法= RequestMethod.POST) –

+1

通過只是將所有3個傑克遜罐類路徑 – ronssm

回答

0

,你必須在你的控制器這樣添加的MediaType在您的請求映射。

@RequestMapping(value = "/inventario/",consumes = MediaType.APPLICATION_JSON, 
       method = RequestMethod.POST) 
public ResponseEntity<Void> insereItem(@RequestBody Item item){...} 
+0

解決我不得不添加像下面,但仍然錯誤415 @RequestMapping(value =「/ inventario」,consumes =「application/json」,method = RequestMethod.POST) – ronssm

+0

也不能這樣工作: @RequestMapping(value =「/ inventario」,consumes = MediaType.APPLICATION_JSON_VALUE,生產= MediaType.APPLICATION_JSON_VALUE,方法= RequestMethod.POST) – ronssm

+0

你能分享你的請求數據和項目DTO代碼嗎? – Rakesh

0

eighter你有刪除的數據類型在發送AJAX請求 即

dataType : "json" 

或者必須產生應用/ JSON響應如下

@RequestMapping(value = "/inventario/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 

它將給出作爲與ajax響應數據類型鍵匹配的JSON對象響應。 你可以使用它們中的任何一個。