@RequestBody接收的是一個Json對象的字符串,而不是一個Json對象。然而在ajax請求每每傳的都是Json對象,後來發現用 JSON.stringify(data)的方式就能將對象變成字符串。同時ajax請求的時候也要指定dataType: "json",contentType:"application/json" 這樣就能夠輕易的將一個對象或者List傳到Java端,使用@RequestBody便可綁定對象或者List.javascript
js寫法java
<script type="text/javascript"> $(document).ready(function(){ var saveDataAry=[]; var data1={"userName":"test","address":"gz"}; var data2={"userName":"ququ","address":"gr"}; saveDataAry.push(data1); saveDataAry.push(data2); $.ajax({ type:"POST", url:"user/saveUser", dataType:"json", contentType:"application/json", data:JSON.stringify(saveData), success:function(data){ } }); }); </script>
spring寫法ajax
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }}) @ResponseBody public void saveUser(@RequestBody List<User> users) { userService.batchSave(users); }
RequestMappingHandlerAdapterspring
RequestResponseBodyMethodProcessorjson
AbstractMessageConverterMethodArgumentResolverapp
HttpMessageConverterurl
MappingJackson2HttpMessageConverterspa