介绍
将请求参数封装到 List 中
注意: 由于封装到 List 中,所以必须用此注解,否则会报错
应用场景
比如批量删除等
html 代码
使用jquery实现
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<input type="button" onclick="del()" value="批量删除">
<table>
<tr>
<td></td>
<td>姓名</td>
</tr>
<tr>
<td><input type="checkbox" name="id" value="1"></td>
<td>李雷</td>
</tr>
<tr>
<td><input type="checkbox" name="id" value="2"></td>
<td>韩梅梅</td>
</tr>
<tr>
<td><input type="checkbox" name="id" value="3"></td>
<td>lucy</td>
</tr>
</table>
<script>
function del() {
var ids =[];
$('input[name="id"]:checked').each(function(){
ids.push($(this).val());
});
$.ajax({
url:'/deleteByIds',
type:'post', //使用post方法
dataType:'json',//服务器端返回的数据格式是json
data: {
"ids":ids,
},//发给服务器端的数据
success:function(data){ //data:服务器端返回给浏览器端的数据
if(data.code==0){
alert(data.msg);
}else{
alert(data.msg)
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
}
</script>
点击按钮,查看浏览器提交的数据,如下图:
使用jquery库,请求中的参数名是:ids[]
Controller 代码
需要使用 @RequestParam(name = "ids[]")
指定请求中的参数名,由上图可知,请求中的参数名是:ids[]
形参是 数组
@RestController
public class DelCtrl {
@RequestMapping("/deleteByIds")
public JsonResult deleteByIds(@RequestParam("ids[]")String[] ids){
for(Object id:ids){
System.out.println(id);
}
return new JsonResult(0,"删除成功!");
}
}
形参是 List
@RestController
public class DelCtrl {
@RequestMapping("/deleteByIds")
public JsonResult deleteByIds(@RequestParam("ids[]") List ids){
for(Object id:ids){
System.out.println(id);
}
return new JsonResult(0,"删除成功!");
}
}