SpringBoot参数传递&bean自动填充
1.前端传递基本数据类型数组
前端ajax
var item = new Array();
var resources = new Array();
bind.forEach(function (value,index) {
$('select#item').get(0).selectedIndex=index;
item.push($('select#item').val()[0]);
resources.push(value);
})
$.ajax({
url:'/workFlow/get/flow',
traditional:true,
method:'POST',
data:{items:item,resources:resources},
error:function(xhr,error,exception){
alert(error+'\r\n'+exception);
},
success:function(){
alert("success");
}
})
后端
@PostMapping(value = "/get/flow")
public ModelAndView getFlow(@RequestParam(value = "items") String[] items,@RequestParam(value = "resources")List<List<String>> resources){
for(int i=0;i<items.length;i++){
System.out.println(items[i]);
}
System.out.println(resources.size());
for(List<String> list:resources){
System.out.println(list.size());
for(String resource:list){
System.out.print(resource);
}
System.out.println();
}
return new ModelAndView("index");
}
2.前端传递bean数组
前端
var _data = $("#bootstrap-table").bootstrapTable('getData',false);
$.ajax({
type:'post',
url:'/resources/updateSys',
cache:false,
traditional:true,
data:JSON.stringify(_data),
dataType:'json',
contentType:'application/json',
error:function(xhr,error,infos){
alert(error+"\r\n"+infos);
},
success:function(data,status){
//tableDatas=$('#bootstrap-table').bootstrapTable('getData');
alert("更新成功");
}
});
后端
@PostMapping(value="/updateSys")
public void updateResourceSys(@RequestBody ResourceSyss[] datas) {
for(ResourceSyss data:datas) {
System.out.println("out : "+data.toString());
}
}
3.总结和注意事项
- 在传递对象数组时,对象bean必须有setXX方法,因为注入方式是采用setXX方法注入;
- 传递对象数组时,必须使用@RequestBody注解,而传递基本数据类型时可以采用@RequestParam注解
- 使用@RequestParam时,上面例子里,value=“items”如果ajax里traditional=false则需改成value=“items[]”