springmvc数组/集合传参方式

    平时开发过程中,经常遇到要对某个表进行批量的CRUD操作,这涉及到一个前台向后台的数组/集合传值问题,方式有多种,殊途同归,简单记录下。

目录

1.controller核心代码

2.HTML前台代码

3.简单小结


 

1.controller核心代码

    @PostMapping(value = "/findLabelBatch01")public RetResult> findLabelBatch01(@RequestParam("ids[]") List ids) {return RetResponse.makeOKRsp(service.getLabelByIds(ids));}@PostMapping(value = "/findLabelBatch02")public RetResult> findLabelBatch02(@RequestParam("id") List ids) {return RetResponse.makeOKRsp(service.getLabelByIds(ids));}@PostMapping(value = "/findLabelBatch03")public RetResult> findLabelBatch03(@RequestBody List ids) {return RetResponse.makeOKRsp(service.getLabelByIds(ids));}@PostMapping(value = "/findLabelBatch04")public RetResult> findLabelBatch03(String datas) {List ids = JSON.parseArray(datas, Long.TYPE);return RetResponse.makeOKRsp(service.getLabelByIds(ids));}

2.HTML前台代码








3.简单小结

1.以上四种方式都可以达到前台向controller传递集合/数组,并成功返回结果的目的;
2.findLabelBatch01/findLabelBatch02/findLabelBatch04都是用来处理$.ajax中ContentType的默认类型application/x-www-form-urlencoded编码的内容,此时接收的参数是来自于requestHeader中,即请求头,也就是在url中,格式为xxx?username=root&password=root;
3.@RequestParam注解加与不加正常情况下区别不大,但是加了@RequestParam后声明的参数默认必须有实参传递,否则报错,修改为@RequestParam(value = "id",required = false)后则与不加@RequestParam时一致。
4.findLabelBatch03中@RequestBody注解接收的参数则是来自于requestBody中,即请求体中,一般用于传递contextType类型为非application/x-www-form-urlencoded编码的内容,只能用于post请求,此处demo传递简单的json格式参数。
5.一般情况下,只有一个参数,一般是根据id批量删除时,推荐采用findLabelBatch02的方式传递,传参可单可多,灵活方便。当参数比较复杂时,比如传递对象数组时,推荐采用findLabelBatch04的方式传递,简单无脑,基本万能。

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部