日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot的數據校驗(@Validated注解)、關于validation無法導入的問題解決、自定義校驗注解

作者:@黑夜中的一盞明燈 更新時間: 2022-07-30 編程語言

一:SpringBoot的數據校驗(@Validated注解)、關于validation無法導入的問題解決

在springboot中,@Validated可對后臺接收model進行數據校驗,不符合則拋出異常。
導入依賴:

 <!-- validation組件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

如果在你導入validation包的時候,出現爆紅,檢查springboot的版本,本人親測validation在springboot的2.3.4.RELEASE版本可以導入,不會出現問題其他問題
在這里插入圖片描述

使用樣例:
1.在實體類中定義注解

@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_role")
@ApiModel(value="Role對象", description="")
public class Role implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @NotNull(message = "角色名稱不能為空")
    private String name;

    @NotNull(message = "角色編碼不能為空")
    private String code;

    @ApiModelProperty(value = "備注")
    private String remark;

    private LocalDateTime created;

    private LocalDateTime updated;

    private Integer statu;

    @TableField(exist = false)
    private List<Long> menuIds = new ArrayList<>();


}

2.在controller層的方法形參前進行聲明

 @PostMapping("/save")
    public Result save(@Validated @RequestBody Role role){
        role.setCreated(LocalDateTime.now());
        role.setStatu(Const.STATIC_OFF);

        roleService.save(role);
        return Result.succ(role);
    }

常用注解:

@AssertFalse 校驗false
@AssertTrue 校驗true
@DecimalMax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 與上類似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull  檢查Null
@Past  檢查日期
@Pattern(regex=,flag=)  正則
@Size(min=, max=)  字符串,集合,map限制大小
@Validate 對po實體類進行校驗(若modelA中存在modelB,可使用@Validate聲明modelB進行校驗,具體校驗規則在modelB進行聲明)

二:自定義校驗注解

在這里插入圖片描述
自定義 @IsMobile注解演示:由于下面的代碼是本人在項目中粘貼出的,會有一些包沒有的現象,請大家見諒。
第一步:新建一個IsMobile類

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { IsMobileValidator.class})
public @interface IsMobile {

    boolean required() default true;

    String message() default "手機號碼格式錯誤";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

第二步:@Constraint(validatedBy = { IsMobileValidator.class})定義校驗類

public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(required){
            return ValidatorUtil.isMobile(value);
        }else{
            if(StringUtils.isEmpty(value)){
                return true;
            }else {
                return ValidatorUtil.isMobile(value);
            }
        }

    }
}

上面使用的ValidatorUtil類

/**
 * 手機號碼校驗
 */
public class ValidatorUtil {
    private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");

    public static boolean isMobile(String mobile){
        if(StringUtils.isEmpty(mobile)){
            return false;
        }
        Matcher matcher = mobile_pattern.matcher(mobile);
        return matcher.matches();
    }


}

原文鏈接:https://blog.csdn.net/qq_51269815/article/details/124919509

欄目分類
最近更新