2016-02-13 54 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对象响应。 你可以使用它们中的任何一个。

相关问题