使用@Aspect自定义注解实现请求参数非空校验

本类实现过程已被打入owlMagicComment jar包,地址:

<!-- https://mvnrepository.com/artifact/com.github.engwen/owlMagicComment -->
<dependency>
    <groupId>com.github.engwen</groupId>
    <artifactId>owlMagicComment</artifactId>
    <version>1.1.4</version>
</dependency>
直接使用jar的童鞋  移驾 https://blog.csdn.net/qq_15674631/article/details/83821413

 

1.自定义注解

package com.owl.annotations;

import java.lang.annotation.*;

/**
 * 添加參數注解
 * author engwen
 * email xiachanzou@outlook.com
 * time 2018/10/15.
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OwlCheckParams {

    String[] notAllNull() default {};

    String[] notNull() default {};

    String[] canNull() default {};
}

 

2.自定义注解实现

 

package com.owl.asImpl;

import com.owl.annotations.OwlCheckParams;
import com.owl.magicUtil.model.MsgConstant;
import com.owl.magicUtil.util.ClassTypeUtil;
import com.owl.magicUtil.util.RegexUtil;
import com.owl.magicUtil.vo.MsgResultVO;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 參數注解功能實現
 * author engwen
 * email xiachanzou@outlook.com
 * time 2018/10/15.
 */
@Aspect
@Component
@Order(91)
public class OwlCheckParamsAS {
    private static Logger logger = Logger.getLogger(OwlCheckParamsAS.class.getName());

    @Pointcut("@annotation(com.owl.annotations.OwlCheckParams)")
    public void checkParamsCut() {
    }

    @Around("checkParamsCut()")
    public Object checkParams(ProceedingJoinPoint joinPoint) throws Throwable {
        MsgResultVO result = new MsgResultVO();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//        獲取被標記不能爲空的屬性集合
        String[] notNull = methodSignature.getMethod().getAnnotation(OwlCheckParams.class).notNull();
        String[] notAllNull = methodSignature.getMethod().getAnnotation(OwlCheckParams.class).notAllNull();
//        其中是否存在空,默認不存在
        boolean hasNull = false;
        boolean allOrNull = true;
//        存放含有空的屬性
        List<String> paramsIsNull = new ArrayList<>();

//        此處從requestHead頭中獲取參數,
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String[]> paramsHeadMap = request.getParameterMap();

        if (null != paramsHeadMap && paramsHeadMap.keySet().size() > 0) {
            for (String param : notNull) {
                if (null == paramsHeadMap.get(param) || paramsHeadMap.get(param).length == 0) {
                    paramsIsNull.add(param);
                    hasNull = true;
                }
            }
            for (String param : notAllNull) {
                if (null != paramsHeadMap.get(param) && paramsHeadMap.get(param).length > 0) {
                    allOrNull = false;
                    break;
                }
            }
        } else {
//          獲取參數
            Map<String, Object> paramsBodyMap = new HashMap<>();
            Object paramsVO = joinPoint.getArgs()[0];
            if (ClassTypeUtil.isPackClass(paramsVO) || ClassTypeUtil.isBaseClass(paramsVO)) {
                logger.debug("本注解仅限使用对象或Map接收参数时使用");
            } else {
//                使用Map接收参数
                if (paramsVO instanceof Map) {
                    paramsBodyMap = (Map<String, Object>) paramsVO;
                } else {
//                  使用对象接收参数
                    Field[] fields = paramsVO.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        paramsBodyMap.put(field.getName(), field.get(paramsVO));
                    }
                }
                for (String param : notNull) {
                    if (RegexUtil.isEmpty(paramsBodyMap.get(param))) {
                        paramsIsNull.add(param);
                        hasNull = true;
                    }
                }
                for (String param : notAllNull) {
                    if (!RegexUtil.isEmpty(paramsBodyMap.get(param))) {
                        allOrNull = false;
                        break;
                    }
                }
            }
        }
        if (hasNull) {
            logger.debug("请求参数错误");
            return result.errorResult(MsgConstant.REQUEST_PARAMETER_ERROR.getCode(), backStr("请求参数 %s 不能为空", paramsIsNull));
        } else if (notAllNull.length > 0 && allOrNull) {
            logger.debug("请求参数错误");
            return result.errorResult(MsgConstant.REQUEST_PARAMETER_ERROR.getCode(), backStr("请求参数 %s 不能全为空", Arrays.asList(notAllNull)));
        } else {
            logger.debug("参数校验成功");
            return joinPoint.proceed(joinPoint.getArgs());
        }
    }

    private static String backStr(String str, List arr) {
        String temp = arr.toString();
        return String.format(str, temp.substring(1, temp.length() - 1));
    }

}

 

 原始代码:
 
        @RequestMapping("/signin")
        public MsgResultVO signin(User user) {
            MsgResultVO result = new MsgResultVO();
            if(null==user.getPassword || "" == user.getPassword ){
                result.errorMsg("密码不能为空");
            } else if(null==user.getAccount || ""==user.getAccount ){
                result.errorMsg("账号不能为空");
            } else {
                result = userService.signin(user);
            }
            return result;
        }
 
 
      使用注解后代码:
 
        @RequestMapping("/signin")
        @OwlCheckParams(notNull={"account","password"})
        public MsgResultVO signin(User user) {
            return userService.signin(user);
        }
 
 
      返回数据均为{"result":false,"resultCode":"0002","resultMsg":"请求参数 password 不能

为空","resultData":null,"params":{}}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值