如何在Spring中迭代@RequestParam?

时间:2017-01-06 21:59:47

标签: java spring spring-mvc spring-boot

我在Spring中构建一个API,我有一个简单的问题:

我想在执行某些逻辑之前对下面的这些参数进行检查以查看它们是否包含值。

我是春天的新手 - 无论如何要去做"得到"将这些值分解为某种数据结构,以便我可以执行检查吗?

        @RequestParam(value = "video") MultipartFile video,
        @RequestParam(value = "pictureOne") MultipartFile pictureOne,
        @RequestParam(value = "pictureTwo") MultipartFile pictureTwo,
        @RequestParam(value = "pictureThree") MultipartFile pictureThree,
        @RequestParam(value = "pictureFour", required = false) MultipartFile pictureFour,
        @RequestParam(value = "pictureFive", required = false) MultipartFile pictureFive,
        @RequestParam(value = "pictureSix",  required = false) MultipartFile pictureSix,
        @RequestParam(value = "pictureSeven", required = false) MultipartFile pictureSeven,
        @RequestParam(value = "pictureEight", required = false) MultipartFile pictureEight,
        @RequestParam(value = "pictureNine", required = false) MultipartFile pictureNine,
        @RequestParam(value = "pictureTen", required = false) MultipartFile pictureTen)

1 个答案:

答案 0 :(得分:1)

如果要对所有这些值执行验证并在结构中关闭它,我建议创建DTO对象并将所有变量放在字段中,例如:

public class FilesDto{
    private MultipartFile video;
    private MultipartFile photos[];
}
//Getters setters...

然后在您的控制器中

@Autowired
private SomeValidator someValidator;

@RequestMapping(method = RequestMethod.POST)
public void savePhotos(@Valid FilesDto filesDto) {
    ....
}

@InitBinder("filesDto")
protected void initBinde(WebDataBinder binder) {
    binder.setValidator(someValidator);
}

其中someValidator是实现Validator接口的类。 根据@mbridges的评论,我还强烈建议使用数组而不是列出所有参数。