溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot如何進行接入?yún)?shù)驗證

發(fā)布時間:2021-09-29 17:09:03 來源:億速云 閱讀:119 作者:柒染 欄目:大數(shù)據(jù)

本篇文章為大家展示了springboot如何進行接入?yún)?shù)驗證,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

使用環(huán)境 jdk1.8 spring 4及以上

1、添加jar 包

        <dependency>
            <groupId>com.github.fashionbrot</groupId>
            <artifactId>mars-validated</artifactId>
            <version>1.0.2</version>
        </dependency>

2、開啟使用 valid 2種方式

@SpringBootApplication
@EnableValidatedConfig(fileName = "test")  // fileName 默認中文jar包自帶 如需要批量自定義請自己創(chuàng)建 test.properties  放在自己項目中的resources 下
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@Component
@Configuration
@EnableValidatedConfig(fileName = "valid_zh_CN") //默認讀取 mars-validated  resources 下的 valid_zh_CN,所以不寫默認讀取中文
public class ValidConfig {
}

3、自定義實現(xiàn)全局異常處理

攔截 ValidatedException異常類

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public RespVo exception(Exception e) {
        log.error("exception error:",e);
        return RespVo.fail(RespCode.FAIL.getMsg());
    }
    /**
     * 參數(shù)驗證全局處理
     * @param e
     * @return
     */
    @ExceptionHandler(ValidatedException.class)
    @ResponseStatus(HttpStatus.OK)
    public RespVo ValidationException(ValidatedException e){
        if (log.isDebugEnabled()){
            log.debug("filedName:{} errorMsg:{}",e.getFieldName(),e.getMsg());
        }
        return RespVo.fail(e.getMsg(),RespCode.PARAMETER_ERROR.getCode());
    }
}

4、開始使用 @Validated //接口開啟驗證

@Controller
public class TestController {

    @Autowired
    private ValidService validService;

    @RequestMapping("/test")
    @ResponseBody
    @Validated //接口開啟驗證
    public String test( String abc,@Custom(min = 1,msg="請求參數(shù)失敗") String abc1){
        return abc+":"+abc1;
    }
    //group 驗證參數(shù)
    @RequestMapping("/test1")
    @ResponseBody
    @Validated(groups = {EditGroup.class})
    public String test1( @Custom(min = 1,groups = {EditGroup.class,AddGroup.class}) String abc1){
        return abc1;
    }

    //group 驗證 bean
    @RequestMapping("/test2")
    @ResponseBody
    @Validated(groups = AddGroup.class)
    public String test2(GroupModel groupModel){
        return groupModel.getAbc();
    }
}

5、注解

AnnotationSupported data types作用
NotBlankString驗證String 字符串是否為空
NotNullString,Object,Integer,Long,Double,Short,Float,BigDecimal, BigInteger驗證對象是否為空
NotEmptyString驗證字符串不能為空
AssertFalseBoolean,boolean,String只能為false
AssertTrueBoolean,boolean,String只能為true
BankCardString驗證銀行卡
CreditCardString驗證信用卡
DefaultInteger,Double,Long,Short,Float,BigDecimal,String設置默認值
DigitsString驗證是否是數(shù)字
EmailString驗證是否是郵箱
IdCardString驗證是否是身份證,驗證18歲
Lengthint,long,short,double,Integer,Long,Float,Double,Short,String驗證長度
PatternString正則表達式驗證
PhoneString驗證手機號是否正確
Sizeint,long,short,Integer,Long,Short驗證大小值
NotEqualSizeString驗證長度

6、自定義注解

(1)定義注解
@Documented
@Target({ElementType.FIELD,  ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {CustomConstraintValidator.class,CustomConstraintValidator2.class})//可對應多個或一個實現(xiàn)類
//CustomConstraintValidator 實現(xiàn)類1
//CustomConstraintValidator2 實現(xiàn)類2
public @interface Custom {

//com.sgr.valid.Custom.msg  jar包下的 valid_zh_CN.properties 下對應的msg
    String msg() default "com.sgr.valid.Custom.msg";

    int min();

    Class<?>[] groups() default  {};
}
(2)實現(xiàn)類 CustomConstraintValidator 如同 CustomConstraintValidator2
public class CustomConstraintValidator implements ConstraintValidator<Custom, Object> {

    @Override
    public boolean isValid(Custom custom, Object var1) {
        /**
         * 自定義方法
         */
        int min=custom.min();
        /**
         * valud
         */
        System.out.println(var1);
        var1="567";
        /**
         * return true 則驗證成功 false 驗證失敗
          */
        return false;
    }

   //可實現(xiàn)對參數(shù)的修改
    @Override
    public Object modify(Custom annotation, Object var) {
        System.out.println("CustomConstraintValidator:"+var);
        return var+"1";
    }
}


上述內容就是springboot如何進行接入?yún)?shù)驗證,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI