日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot-服务端参数验证-JSR-303验证框架

發(fā)布時間:2025/3/20 javascript 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot-服务端参数验证-JSR-303验证框架 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. springboot 默認集成了 hibernate-validator,它默認是生效的,可以直接使用。

比如:

@RestController @RequestMapping("/hibernate") public class DefaultHibernateValidatorTestController {/*** Springboot 默認會驗證 controller 層的 validator,使用的是默認實現(xiàn) hibernate-validator。* 但是 hibernate-validator 只能對Object類型的屬性進行校驗,不能對單個的參數(shù)進行校驗。下面的校驗不生效* @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攔截器,可以實現(xiàn)對方法參數(shù)的校驗。

例如:

/*** 對基礎類型的驗證,必須要在Controller類上加 @Validated,同時配置 MethodValidationPostProcessor 才生效* <pre>* @Bean* public MethodValidationPostProcessor methodValidationPostProcessor() {* return new MethodValidationPostProcessor();* }* </pre>* @link https://yezhwi.github.io/springboot/2017/11/17/SpringBoot-服務端參數(shù)驗證-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 驗證的話,需要單獨配置攔截器

?

總結(jié)

以上是生活随笔為你收集整理的SpringBoot-服务端参数验证-JSR-303验证框架的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。