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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot参数校验,对象的某属性校验

發布時間:2024/10/5 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot参数校验,对象的某属性校验 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對于前端來的數據,后端難免要進行合法性校驗,這里可以采用springboot自帶的Validated注解來實現,詳細方法如下:

實體類:

public class User implements Serializable { // @NotNull(message = "id can not be null")private Integer id;private String name;@NotEmpty(message = "username can not be empty")@Length(max = 40, min = 5, message = "username length must between 5 and 10")private String username;@Emailprivate String email;//@Pattern(regexp = "^((13[0-9])|(15[^4,\\\\D])|(18[0,5-9]))\\\\d{8}$",//message = "phone number illegal")@Phone//自定義的注解private String phone;private Integer latest;@NotEmpty(message = "passwd can not be empty")@Length(max = 42, min = 5, message = "password lenth must between 5 and 42")private String passwd;private byte isDel;//默認值為0private Timestamp lastAlter; } 再在對應的web接口添加@Validated注解即可:

在校驗不通過的時候,springboot會拋MethodArgumentNotValidException異常,直接把異常信息給客戶端不友好,我們可以使用springboot的全局異常捕獲來處理此異常,代碼如下:

對于簡單參數的非空等校驗可以使用Spring提供的Assert類,參考博客:https://blog.csdn.net/qq_41633199/article/details/105165740。有時候springboot自帶注解的可能不能滿足我們的使用,這時我們可以自己實現一個注解與校驗邏輯來進行加強,方式如下:

1:先新增一個注解:

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint( validatedBy = PhoneConstraint.class) //指定該注解在對應的屬性上可以重復使用 @Repeatable(value = Phone.List.class) public @interface Phone {String message() default "tfq.validator.constraints.phone.message";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@interface List{Phone[] value();} }

注解的groups()與payload()的作用可以參考這篇文章:https://reflectoring.io/bean-validation-with-spring-boot/

以及https://blog.csdn.net/blueheart20/article/details/88817754

?

再新增校驗類PhoneConstraint.java,引用springboot的一個接口,以實現我們的校驗邏輯以及確保校驗類能被springboot加載到。

public final class PhoneConstraint implements ConstraintValidator<Phone, Object> { private static final Pattern phonePattern = Pattern.compile("^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$"); {System.out.println("自定義直接被調用了");}@Overridepublic void initialize(Phone constraintAnnotation) {}@Overridepublic boolean isValid(Object phone, ConstraintValidatorContext constraintValidatorContext) {String phoneStr = "";if (phone instanceof String || phone instanceof Number){phoneStr = String.valueOf(phone);} else {return false;}if (phoneStr == null || "".equals( phoneStr.trim() )){return true;}Matcher phoneMatcher = phonePattern.matcher(phoneStr);return phoneMatcher.matches();}

這里的實現類不需要申明為bean,在第一次需要校驗的時候,springboot會加載此類,生成一個此類的對象,后續校驗直接通過原對象調用方法進行校驗,就是說默認是單例的。

?

?

?

?

總結

以上是生活随笔為你收集整理的springboot参数校验,对象的某属性校验的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。