接⼝⼊参验证
(@RequestParam@Valid@Validated@RequestBody)
今天了解了下接⼝⼊参验证问题:
1.
@RequestParam 适⽤于Get请求且content-type为application/x-www-form-urlencoded
@RequestBody 适⽤于post请求且content-type为⾮application/x-www-form-urlencoded类型,⼀般为application/json
2.
(1)⼊参为@RequestParam或@RequestBody时,不⽤加@valid和@validated;
(2)⼊参为@NotNull时要在⽅法上加@valid或@validated,或者在类上加@Validated(@valid不能作⽤于类上),这样@NotNull才能起作⽤。
@Valid
@GetMapping("/exam-info")
public Boolean getInfo(@NotNull(message="examId不能为空")Long examId){......}
(3)当⼊参为实体对象时,需要在⽅法上加@Valid或@Validated或者在参数前加@Valid或@Validated,或者在类上加@Validated
@Valid
@GetMapping("/exam-info")
public Boolean getInfo(Ur ur){......}
@GetMapping("/exam-info")
public Boolean getInfo(@Valid Ur ur){......}
@Validated
@GetMapping("/exam-info")
public Boolean getInfo(Ur ur){......}
@GetMapping("/exam-info")
public Boolean getInfo(@Validated Ur ur){......}
public Class Ur{
@NotNull("id不能为空")
private Integer id;
.
.
.
}
4.嵌套验证
@valid作⽤于属性上有嵌套验证作⽤,@validated不能作⽤于属性上,如下代码在Ur类的属性car上添加@valid注解,当传参id为空时会报错。
@GetMapping("/exam-info")
public Boolean getInfo(@Valid Ur ur){.....}
@GetMapping("/exam-info")
public Boolean getInfo(@Validated Ur ur){.....}
public class Ur{
@Valid
@NotNull("car不能为空")
private Car car;
........
}
public class Car{
@NotNull("id不能为空")
private Integer id;
........
}