springboot 参数校验使用示例

接收基本类型参数

在使用多个基本类型接收参数时,@Validated 要写在 controller 上,写在方法、方法参数前都不行,@Valid 无法使用,如果只是验证 @NotNull,可以直接在方法参数前使用 @RequestParam

@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @PostMapping("/singleField")
    public String singleField(@NotNull String age, @RequestParam(value = "name") String name) {
        return name + age;
    }
}

使用封装类接收参数

使用封装类接收参数时,使用 @Validated@Valid 效果是一样的,这两个都只能写在方法参数前才能生效,如果类的数据也是类,并且需要嵌套校验,则需要在属性上使用 @Valid 注解。在使用 @RequestBody 接收数据时校验方法相同

@Data
public class Album {
    @NotNull
    private Integer musicCount;
    @NotNull
    private String[] musics;
    @NotNull @Size(min = 2) @Valid
    private List<Person> musicians;
    @NotNull @Size(max = 1) @Valid
    private Person[] people;
    @NotNull @Valid
    private Person person;
}
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private ObjectMapper json;

    @PostMapping("/test")
    public String test(@Validated Album album) throws JsonProcessingException {
        return json.writeValueAsString(album);
    }
}

接收基本类型数组和基本类型集合

使用规则和接收基本类型参数一样,@Validated 要写在 Controller 上,写在方法、方法参数前都不行,@Valid 无法使用

@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @Resource
    private ObjectMapper json;

    @PostMapping("/array")
    public String array(@NotNull @Size(max = 1) String[] strs,@NotNull Integer[] ints) throws JsonProcessingException {
        return json.writeValueAsString(strs)+" "+json.writeValueAsString(ints);
    }
    
	@PostMapping("/test")
    public String test(@RequestBody @Size(min = 2) List<String> strs) throws JsonProcessingException {
        return json.writeValueAsString(strs);
    }
}

接收对象类型数组和集合

注入时必须使用 @RequestBody ,校验时需要在 Controller 上写 @Validated 并且在方法参数前使用 @Valid


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