国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

java實(shí)現表單必填參數驗證的方法

發(fā)布時(shí)間:2021-07-06 11:13 來(lái)源:腳本之家 閱讀:0 作者:任未然 欄目: 開(kāi)發(fā)技術(shù) 歡迎投稿:712375056

一. 概述

在開(kāi)發(fā)后端接口, 通常都會(huì )涉及檢驗參數必填校驗, 一般我們的處理都是很粗暴的寫(xiě)個(gè)if()判斷, 然后拋異常. 本文將介紹通過(guò)代理的思想, 用注解優(yōu)雅的處理非空判斷

二. 實(shí)現過(guò)程

最終想要的效果->在方法的參數加個(gè)注解或者參數的屬性里加個(gè)注解, 注解可以自定義報錯信息, 就可以實(shí)現自動(dòng)非空校驗

2.1 編寫(xiě)注解

@Target({ElementType.FIELD})  //作用的位置
@Retention(RetentionPolicy.RUNTIME) //作用域
@Documented
public @interface NotNull {
    String value() default "{報錯信息}";
}

說(shuō)明: 該注解用來(lái)綁定某個(gè)必填屬性

@Target({ElementType.TYPE,ElementType.METHOD})  //作用的位置
@Retention(RetentionPolicy.RUNTIME) //作用域
@Documented
public @interface CheckParam {
}

說(shuō)明: 該注解用來(lái)綁定某個(gè)類(lèi)或某個(gè)方法,作為校驗代理攔截的標識

2.2 編寫(xiě)校驗代理AOP

@Aspect
@Slf4j
public class CheckParamAop {
    @Around("@within(com.midea.cloud.common.annotation.CheckParam) || @annotation(com.midea.cloud.common.annotation.CheckParam)")
    public Object cacheClear(ProceedingJoinPoint pjp) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            // 方法參數注解類(lèi)型
            Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();
            // 方法參數的類(lèi)型
            Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
            // 獲取方法參數
            Object[] args = pjp.getArgs();
            if(!ObjectUtils.isEmpty(args)){
                // 遍歷參數
                AtomicInteger index = new AtomicInteger(0);
                Arrays.stream(args).forEach(o -> {
                    int indexNo = index.getAndAdd(1);
                    /**
                     * 檢查方法參數非空
                     */
                    Annotation[] parameterAnnotation = parameterAnnotations[indexNo];
                    if(!ObjectUtils.isEmpty(parameterAnnotation)){
                        Arrays.stream(parameterAnnotation).forEach(annotation -> {
                            if(annotation instanceof NotNull){
                                NotNull notNull = (NotNull)annotation;
                                // 注解信息
                                String message = notNull.value();
                                // 通過(guò)工具類(lèi)獲取多語(yǔ)言信息
                                String localeMsg = LocaleHandler.getLocaleMsg(message);
                                // 檢查參數非空
                                Optional.ofNullable(o).
                                        filter(o1 -> !ObjectUtils.isEmpty(o1)).
                                        orElseThrow(()->new BaseException(localeMsg));
                            }
                        });
                    }

                    /**
                     * 檢查方法參數屬性非空
                     */
                    Class<?> parameterType = parameterTypes[indexNo];
                    Field[] fields = parameterType.getDeclaredFields();
                    if(!ObjectUtils.isEmpty(fields)){
                        // 遍歷屬性
                        Arrays.stream(fields).forEach(field -> {
                            NotNull annotation = field.getAnnotation(NotNull.class);
                            if(null != annotation){
                                Object value = null;
                                // 注解信息
                                String message = annotation.value();
                                // 通過(guò)工具類(lèi)獲取多語(yǔ)言信息
                                String localeMsg = LocaleHandler.getLocaleMsg(message);
                                Optional.ofNullable(o).orElseThrow(()->new BaseException(localeMsg));
                                try {
                                    field.setAccessible(true);
                                    value = field.get(o);
                                } catch (Exception e) {
                                    log.error("獲取屬性值報錯"+e.getMessage());
                                    log.error("獲取屬性值報錯"+e);
                                }
                                // value為空時(shí)報錯
                                Optional.ofNullable(value).
                                        filter(o1 -> !ObjectUtils.isEmpty(o1)).
                                        orElseThrow(()->new BaseException(localeMsg));
                            }
                        });
                    }
                });
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e){
            log.error("檢查參數aop報錯:"+e.getMessage());
            log.error("檢查參數aop報錯:"+e);
        }
        return pjp.proceed();
    }
}

三. 使用示例

public class Test{
    @Data
    class Demo{
        @NotNull("名字不能為空!")
        private String name;
        private String sex;
        private Integer age;
    }

    @CheckParam
    public void testNoNullCheck1(Demo demo) {

    }
    @CheckParam
    public void testNoNullCheck2(@NotNull("user不能為空") User user) {

    }
}

到此這篇關(guān)于java實(shí)現表單必填參數驗證的方法的文章就介紹到這了,更多相關(guān)java 表單必填參數驗證內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

隔壁白嫩少妇夹得真紧| 啦啦啦啦WWW视频免费观看| 亚洲欧美日韩综合一区在线观看| 在线天堂资源WWW在线中文| 亚洲女人被黑人巨大进入| 加勒比色综合久久久久久久久|