java url中如何传递数组,springMVC框架controller类如何接收数组参数?
下面介绍一下URL中传递数组参数方法:
dd.do?titles[]=col1&titles[]=col2&titles[]=col3
或者使用ajax方式传递:
varparam = {titles:['col1','col2','col3']}; $.ajax({url:"dd.php", type:"post", data:param, async:false, dataType:"json",/**这个类型很重要 */cache:false, error:function(data){rtnObj = data.responseText; }, beforeSend:function(XMLHttpRequest){//ajaxStart(); }, complete:function(XMLHttpRequest, textStatus){//ajaxComplete(); }, success:function(data){rtnObj = data; }});
在springMVC中controller类接收数组参数的方法:
@RequestMapping(value="/save", method = RequestMethod.POST) @ResponseBodypublicStringsave(@RequestParam(value="titles[]") String[] titles){ System.out.println(titles);returnnull; }
varids=[1,2,3,4,5,6];$.ajax({url:"/postArray",type:"post",dateType:'json',data:{ids:ids},success:function(res){console.log("数据=="+res);},error:function(err){alert("fail",err);}})
@RequestMapping("/postArray")publicStringpostArray(@RequestParam(value="ids[]")String[]ids){for(inti=0;i<ids.length;i++){System.out.println(ids[i]);}return"success";}
@DatapublicclassCaiPuEntityimplementsSerializable{privatestaticfinallongserialVersionUID=1L;privateLong id;privateString weekDay;//星期几@JSONField(format="yyyy年MM月dd日")privateDate startDate;//开始日期@JSONField(format="yyyy年MM月dd日")privateDate endDate;//结束日期privateString foodOne;privateString foodTwo;privateString foodThird;privateString foodFour;privateString foodFive;}
varfood_day1={weekDay:"星期一",startDate:"2019年04月10日",endDate:"2019年04月10日",foodOne:"黄焖鸡",foodTwo:"黄焖鸡",foodThird:"黄焖鸡",foodFour:"黄焖鸡",foodFive:"黄焖鸡",};varfood_day2={weekDay:"星期一",startDate:"2019年04月10日",endDate:"2019年04月10日",foodOne:"鸡公煲",foodTwo:"鸡公煲",foodThird:"鸡公煲",foodFour:"鸡公煲",foodFive:"鸡公煲",};varcaipus=newArray();caipus[0]=food_day1;caipus[1]=food_day2;//发送请求传递参数$.ajax({url:add_url,data:JSON.stringify(caipus),type:"post",cache:false,dataType:"json",contentType:"application/json",crossDomain:true==!(document.all),success:function(res){console.log("新增==:"+JSON.stringify(res));},error:function(res){alert("联网失败,请检查网络");}});
//新增数据@PostMapping("/add")publicStringadd(@RequestBodyList<CaiPuEntity>caiPuEntityList){log.info("新增="+JSON.toJSONString(caiPuEntityList));return"新增成功";}