@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