@RequestParam参数校验
如下所示:
- 第一步、在springMVC注入org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
- 第二步、重写校验异常
- 第三步、在方法所在的类添加@Validated注解
- 第四步、在需要校验的参数前面添加校验规则
比如
接口入参验证(@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才能起作用。
1
2
3
|
@Valid
@GetMapping ( "/exam-info" )
public Boolean getInfo( @NotNull (message= "examId不能为空" )Long examId){......}
|
(3)当入参为实体对象时,需要在方法上加@Valid或@Validated或者在参数前加@Valid或@Validated,或者在类上加
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@Validated
@Valid
@GetMapping ( "/exam-info" )
public Boolean getInfo(User user){......}
@GetMapping ( "/exam-info" )
public Boolean getInfo( @Valid User user){......}
@Validated
@GetMapping ( "/exam-info" )
public Boolean getInfo(User user){......}
@GetMapping ( "/exam-info" )
public Boolean getInfo( @Validated User user){......}
public Class User{
@NotNull ( "id不能为空" )
private Integer id;
.
.
.
}
|
(4)嵌套验证
@valid作用于属性上有嵌套验证作用,@validated不能作用于属性上,如下代码在User类的属性car上添加@valid注解,当传参id为空时会报错。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@GetMapping ( "/exam-info" )
public Boolean getInfo( @Valid User user){.....}
@GetMapping ( "/exam-info" )
public Boolean getInfo( @Validated User user){.....}
public class User{
@Valid
@NotNull ( "car不能为空" )
private Car car;
........
}
public class Car{
@NotNull ( "id不能为空" )
private Integer id;
........
}
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/duzjextjs/p/10603373.html