Java參數(shù)校驗詳解之使用@Valid注解和自定義注解進行參數(shù)驗證
很多時候我們需要使用不少if、else等等邏輯判斷及驗證,這樣在進行一些重復(fù)的參數(shù)校驗會很麻煩,且以后要維護也會吃力。
而這樣就可以使用javax.validation。驗證(Validation)常見的驗證操作包括驗證數(shù)據(jù)的類型、格式、長度、范圍、唯一性等
javax.validation 包:Java SE 6+ 中引入了 javax.validation 包,作為 Bean Validation 規(guī)范的一部分。這個包提供了一組注解和接口,可以方便地進行數(shù)據(jù)驗證。
<!-- validation組件依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
而對于一般寫在業(yè)務(wù)邏輯類中的參數(shù)校驗語句,可以省略。如將@Valid注解填寫在登錄接口的方法參數(shù)中:
@PostMapping("/login") public RespBean login(@Valid @RequestBody User user) { log.info("{}", user); return userService.login(user); }
@Valid 注解對入?yún)⑦M行相應(yīng)的校驗:
注解使用在方法參數(shù)上,然后對于參數(shù)的校驗要求可去參數(shù)的實體類進行校驗條件的填寫。
/** * @author Z * @date 2023/9/27 21:25 */ @Data public class User { @NotNull //賬號非空 //這個@Mobile是自定義判斷注解,下面有對其的創(chuàng)建進行詳細的講解 @Mobile(required = true) private String mobile; ? @NotNull //密碼非空 @Length(min = 32) //長度的限制 private String password; }
以及如: @Size(min=1, max=12) 代表:長度在 1 ~ 12 字符之間。其他一些判斷的注解可以去該導入的外部庫查看。
也可以自定判斷條件注解:如@Mobile這個自定義的注解:
1.創(chuàng)建軟件包:Validation
2.創(chuàng)建需要的注解:Mobile
3.而對于這個注解的寫法,直接去拷貝javax.validation 包中已經(jīng)寫好的注解,如:@Notnull注解進行修改:(有報錯的地方就刪除不用即可)
@Notnull注解如下:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Repeatable(NotNull.List.class) //爆紅了刪除 @Documented @Constraint(validatedBy = {}) //校驗規(guī)則的定義 public @interface NotNull { String message() default "{javax.validation.constraints.NotNull.message}"; //修改校驗的消息 ? Class<?>[] groups() default {}; ? Class<? extends Payload>[] payload() default {}; ? }
而在這里在添加一條屬性:(代表必填)
boolean required() default true;
自定義的@Mobile如下:
/** * @author Z * @date 2023/9/28 8:53 */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Documented //自己定義校驗規(guī)則的一個類:MobileValidator.class (手機號碼校驗規(guī)則類) //將自定義規(guī)則類放進@Constraint(validatedBy={}) 中 @Constraint(validatedBy = {MobileValidator.class}) public @interface Mobile { ? boolean required() default true; ? //信息,拋出的是BindException,前端頁面接收的話,我們要進行異常的捕獲 String message() default "手機號碼格式錯誤"; ? Class<?>[] groups() default {}; ? Class<? extends Payload>[] payload() default {}; }
而我們需要進行自己定義檢驗規(guī)則,創(chuàng)建一個校驗規(guī)則類,并將其放進@Constraint(validatedBy={}) 中
自定義校驗規(guī)則類:
/** * 手機號碼校驗規(guī)則 * * @author Z * @date 2023/9/28 8:56 */ public class MobileValidator implements ConstraintValidator<Mobile, String> { ? private boolean required = false; ? //初始化:獲取是否需要是必填的 @Override public void initialize(Mobile constraintAnnotation) { //獲取到填的值:true或者false required = constraintAnnotation.required(); } ? @Override public boolean isValid(String value, ConstraintValidatorContext context) { //必填:則使用手機號碼校驗工具類去校驗 if (required){ return ValidatorUtil.Mobile(value); //非必填: }else { if (StringUtils.isEmpty(value)){ //傳的號碼為空 return true; }else { //傳的號碼非空,則使用手機號碼校驗工具類去校驗 return ValidatorUtil.isMobile(value); } } } }
而對于手機號碼的校驗工具類:
添加依賴:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>
使用正則表達進行手機號碼的校驗:
import org.apache.commons.lang3.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; ? /** * 手機號碼校驗類 (使用正則表達式) * * @author Z * @date 2023/9/27 21:45 */ public class ValidatorUtil { ? private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$"); ? public static boolean Mobile(String mobile) { if (StringUtils.isEmpty(mobile)){ return false; } Matcher matcher = mobile_pattern.matcher(mobile); return matcher.matches(); } }
總結(jié)
到此這篇關(guān)于Java參數(shù)校驗詳解之使用@Valid注解和自定義注解進行參數(shù)驗證的文章就介紹到這了,更多相關(guān)Java @Valid注解和自定義注解參數(shù)驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA?2020.3最新永久激活碼(免費激活到?2099?年,親測有效)
分享一下?IntelliJ?IDEA?2020.3.1?最新激活注冊碼,破解教程如下,可免費激活至?2099?年,親測有效,本文給大家分享兩種方法,感興趣的朋友參考下吧2021-01-01解決IDEA2020.2插件lombok報錯問題(親測有效)
這篇文章主要介紹了解決IDEA2020.2插件lombok報錯問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08解決@MapperScan和@Mapper共存之坑XxxMapper?that?could?not?be?fo
這篇文章主要介紹了解決@MapperScan和@Mapper共存之坑XxxMapper?that?could?not?be?found問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06