SpringBoot中如何接受数组参数

937 阅读1分钟

1 起因

实际项目中经常会遇到一对多批量关联的情况

例如,我们需要设置某个老师所教的全部学生,学生有上百人,一个一个添加不如批量一起添加。所以我们创建批量添加接口,入参为学生id的数组,问题来了,我们的controller怎么接受数组参数呢?

2 解决方案

2.1 SpringBoot

笔者认为有两种较好的解决方案:

第一种很容易:

public interface teacherApi {
    @GetMapping(value = "/teacher/relateStudent")
    void relateTempProjects(@RequestBody List<String> studentIds);
}

但是要注意,这种方案前端的请求体必须为数组,无法传递其他信息,如果还需要有其它附加信息(比如还需要班级名称),那么推荐使用第二种

public class RelateStudentRequestBody {
    private String className;
    private List<String> studentIds;
}

public interface teacherApi {
    @GetMapping(value = "/teacher/relateStudent")
    void relateTempProjects(@RequestBody RelateStudentRequestBody relateStudentRequestBody);
}

2.2 Swagger

在SpringBoot中采用第一种方式时,如何编写Swagger注解呢?

@ApiImplicitParam(name = "studentIds", paramType = "query", value = "学生id数组", required = true, dataType = "String", allowMultiple = true)

只需要把allowMultiple设置为true即可