當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot-服务端参数验证-JSR-303验证框架
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot-服务端参数验证-JSR-303验证框架
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. springboot 默認集成了 hibernate-validator,它默認是生效的,可以直接使用。
比如:
@RestController @RequestMapping("/hibernate") public class DefaultHibernateValidatorTestController {/*** Springboot 默認會驗證 controller 層的 validator,使用的是默認實現 hibernate-validator。* 但是 hibernate-validator 只能對Object類型的屬性進行校驗,不能對單個的參數進行校驗。下面的校驗不生效* @param str* @return*/@RequestMapping("/string")public OpResponse valiateString(@NotEmpty(message = "str不能為空") String str){return OpResponse.suc(str);}/*** 檢驗生效* @param foo* @return*/@RequestMapping("/foo")public OpResponse valiateString(@Valid @NotNull Foo foo){return OpResponse.suc(foo);}static class Foo implements Serializable {@NotNullprivate Integer id;@NotEmptyprivate String name;........} }?
2.?hibernate-validator不支持基礎類型的驗證,springboot對其進行了擴展,添加了MethodValidationPostProcessor攔截器,可以實現對方法參數的校驗。
例如:
/*** 對基礎類型的驗證,必須要在Controller類上加 @Validated,同時配置 MethodValidationPostProcessor 才生效* <pre>* @Bean* public MethodValidationPostProcessor methodValidationPostProcessor() {* return new MethodValidationPostProcessor();* }* </pre>* @link https://yezhwi.github.io/springboot/2017/11/17/SpringBoot-服務端參數驗證-JSR-303驗證框架* Created by wangzhiyuan on 2018/8/20*/ @RestController @RequestMapping("/validate") @Validated public class ValidatorTestController {@ResourceBizService bizService;@RequestMapping("/string") // 這個 @NotEmpty 是生效的public OpResponse valiateString(@NotEmpty(message = "str不能為空") String str){bizService.validateTest(str);return OpResponse.suc(str);}/*** 可以看出,springboot默認只會驗證 controller 方法上的 validator 注解,而不會驗證 controller 層以外的。所以,如果要在其他層使用 validator 驗證的話,需要單獨配置攔截器* @return*/@RequestMapping("/blank")public OpResponse blank(){String str = null;bizService.validateTest(str);bizService.validateFooTest(null);return OpResponse.suc(str);}}?
3.?springboot默認只會驗證 controller 方法上的 validator 注解,而不會驗證 controller 層以外的。所以,如果要在其他層使用 validator 驗證的話,需要單獨配置攔截器
?
總結
以上是生活随笔為你收集整理的SpringBoot-服务端参数验证-JSR-303验证框架的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: webpack-dev-server 和
- 下一篇: 我的.gitignore下配置。存在这里