springboot批量接收对象参数,接收List

  • Post author:
  • Post category:其他


在spring java项目开发中有时候遇到新增、更新数据的时候,单个对象接收方式很方便,前端传递json字符串后端使用@RequestBody注解和 TestStudent对象接收即可。

 @RequestMapping(value = "/receive",method = RequestMethod.POST)
    public void receive(@RequestBody TestStudent dto){

            System.out.println(dto.get(i).toString());
        
    }

如果项目中有批量更新和批量创建那么就需要批量接收参数了

以下方法可以使用

先定义一个对象,注意要引入lombok插件

import lombok.Data;

@Data
public class TestStudent {
    private String name;

    private  Integer age;

    private String address;

    private String phone;
}

定义后台controller

@RestController
@RequestMapping("")
public class TestListController {

    Logger logger= LoggerFactory.getLogger(TestListController.class);

    @ApiOperation(value = "批量接收", notes = "批量接收")
    @RequestMapping(value = "/batch/receive",method = RequestMethod.POST)
    public void batchReceive(@RequestBody List<TestStudent> dto){

        for (int i = 0; i <dto.size() ; i++) {
            System.out.println(dto.get(i).toString());
        }

    
    }
}

然后就是postman构造数据模拟请求

[
{
   "name":"小明",
   "age":"18",
   "address":"北京",
    "phone":"1366669969966"
},
{
   "name":"小李",
   "age":"20",
   "address":"上海",
    "phone":"156885488596"
}
]

启动项目,postman发起请求后台即可批量接收到对象了

运行结果如下



版权声明:本文为weixin_48922293原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。