Spring mvc和jquery产生415错误

时间:2017-04-23 01:48:59

标签: jquery spring spring-mvc

我有以下jquery

<script>
var response = '';
$.ajax({ type: "POST",   
     url: "http://localhost:8080/hsv06/checkUserExists",   
     async: false,
     data: "title=foo",
     success : function(text)
     {
         response = text;
     }
});

console.log(response);
</script> 

以下是其他控制器:

@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json")
public @ResponseBody boolean checkUser(@RequestBody Object title){
    System.out.println(title);
    return true;        
}

然而,这会产生以下错误:

POST http://localhost:8080/hsv06/checkUserExists 415 (Unsupported Media Type)
 send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ (index):57

有什么问题?我发送数据的方式有什么问题?

1 个答案:

答案 0 :(得分:0)

415表示不支持的媒体类型。您的服务器使用application / json,因此您的客户端必须提供application / json数据。要修复它,只需将类型添加到您的jquery中,如下所示。

$.ajax({ type: "POST",   
     url: "http://localhost:8080/hsv06/checkUserExists",   
     async: false,
     data: JSON.stringify({title: "food"}),
     // specifying data type
     contentType: "application/json; charset=utf-8",
     success : function(text)
     {
         response = text;
     }
});
  

contentType(默认值:&#39; application / x-www-form-urlencoded;   字符集= UTF-8&#39)

     

将数据发送到服务器时,请使用此内容类型。默认是   &#34;应用程序/ X WWW的窗体-urlencoded;字符集= UTF-8&#34;

您的Spring REST后端应如下​​所示。由于帖子数据是{title:&#34; food&#34;},Spring会将其解析为Map。

@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json")
public @ResponseBody boolean checkUser(@RequestBody Map<String, String> param){
    System.out.println(param);
    return true;        
}