springboot参数校验,对象的某属性校验
對于前端來的數(shù)據(jù),后端難免要進(jìn)行合法性校驗,這里可以采用springboot自帶的Validated注解來實現(xiàn),詳細(xì)方法如下:
實體類:
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;//默認(rèn)值為0private Timestamp lastAlter; } 再在對應(yīng)的web接口添加@Validated注解即可:在校驗不通過的時候,springboot會拋MethodArgumentNotValidException異常,直接把異常信息給客戶端不友好,我們可以使用springboot的全局異常捕獲來處理此異常,代碼如下:
對于簡單參數(shù)的非空等校驗可以使用Spring提供的Assert類,參考博客:https://blog.csdn.net/qq_41633199/article/details/105165740。有時候springboot自帶注解的可能不能滿足我們的使用,這時我們可以自己實現(xiàn)一個注解與校驗邏輯來進(jìn)行加強(qiáng),方式如下:
1:先新增一個注解:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint( validatedBy = PhoneConstraint.class) //指定該注解在對應(yīng)的屬性上可以重復(fù)使用 @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的一個接口,以實現(xiàn)我們的校驗邏輯以及確保校驗類能被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("自定義直接被調(diào)用了");}@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();}這里的實現(xiàn)類不需要申明為bean,在第一次需要校驗的時候,springboot會加載此類,生成一個此類的對象,后續(xù)校驗直接通過原對象調(diào)用方法進(jìn)行校驗,就是說默認(rèn)是單例的。
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的springboot参数校验,对象的某属性校验的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot配置template
- 下一篇: springboot参数检验,Asser