java實(shí)現(xiàn)表單必填參數(shù)驗(yàn)證的方法
在開發(fā)后端接口, 通常都會涉及檢驗(yàn)參數(shù)必填校驗(yàn), 一般我們的處理都是很粗暴的寫個(gè)if()判斷, 然后拋異常. 本文將介紹通過代理的思想, 用注解優(yōu)雅的處理非空判斷
二. 實(shí)現(xiàn)過程最終想要的效果->在方法的參數(shù)加個(gè)注解或者參數(shù)的屬性里加個(gè)注解, 注解可以自定義報(bào)錯(cuò)信息, 就可以實(shí)現(xiàn)自動非空校驗(yàn)
2.1 編寫注解@Target({ElementType.FIELD}) //作用的位置@Retention(RetentionPolicy.RUNTIME) //作用域@Documentedpublic @interface NotNull { String value() default '{報(bào)錯(cuò)信息}';}
說明: 該注解用來綁定某個(gè)必填屬性
@Target({ElementType.TYPE,ElementType.METHOD}) //作用的位置@Retention(RetentionPolicy.RUNTIME) //作用域@Documentedpublic @interface CheckParam {}
說明: 該注解用來綁定某個(gè)類或某個(gè)方法,作為校驗(yàn)代理攔截的標(biāo)識
2.2 編寫校驗(yàn)代理AOP@Aspect@Slf4jpublic 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(); // 方法參數(shù)注解類型 Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations(); // 方法參數(shù)的類型 Class<?>[] parameterTypes = signature.getMethod().getParameterTypes(); // 獲取方法參數(shù) Object[] args = pjp.getArgs(); if(!ObjectUtils.isEmpty(args)){// 遍歷參數(shù)AtomicInteger index = new AtomicInteger(0);Arrays.stream(args).forEach(o -> { int indexNo = index.getAndAdd(1); /** * 檢查方法參數(shù)非空 */ 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();// 通過工具類獲取多語言信息String localeMsg = LocaleHandler.getLocaleMsg(message);// 檢查參數(shù)非空Optional.ofNullable(o).filter(o1 -> !ObjectUtils.isEmpty(o1)).orElseThrow(()->new BaseException(localeMsg)); }}); } /** * 檢查方法參數(shù)屬性非空 */ 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();// 通過工具類獲取多語言信息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('獲取屬性值報(bào)錯(cuò)'+e.getMessage()); log.error('獲取屬性值報(bào)錯(cuò)'+e);}// value為空時(shí)報(bào)錯(cuò)Optional.ofNullable(value).filter(o1 -> !ObjectUtils.isEmpty(o1)).orElseThrow(()->new BaseException(localeMsg)); }}); }}); }} catch (BaseException e) { throw e;} catch (Exception e){ log.error('檢查參數(shù)aop報(bào)錯(cuò):'+e.getMessage()); log.error('檢查參數(shù)aop報(bào)錯(cuò):'+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í)現(xiàn)表單必填參數(shù)驗(yàn)證的方法的文章就介紹到這了,更多相關(guān)java 表單必填參數(shù)驗(yàn)證內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用Python webdriver圖書館搶座自動預(yù)約的正確方法2. Linux刪除系統(tǒng)自帶版本Python過程詳解3. ASP基礎(chǔ)知識VBScript基本元素講解4. Python 合并拼接字符串的方法5. Python 利用Entrez庫篩選下載PubMed文獻(xiàn)摘要的示例6. Python3 json模塊之編碼解碼方法講解7. Python 制作查詢商品歷史價(jià)格的小工具8. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條9. Python sublime安裝及配置過程詳解10. python 使用事件對象asyncio.Event來同步協(xié)程的操作

網(wǎng)公網(wǎng)安備