SpringBoot使用aspectj實現註解登錄驗證攔截

1,導入Maven依賴

		<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>

2,編寫註解類LoginRequired.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author David
 * @className LoginRequired
 * @date 2020/3/17 14:56
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}

3,使用aspectj的around通知增強攔截

@Aspect
@Component
public class LoginAspect {


    @Autowired
    private RedisUtils redisUtils;

    private Logger logger = LoggerFactory.getLogger(LoginAspect.class);

    @Pointcut("execution(* com.sdzh..controller.*.*(..))")
    public void pointcut(){}

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

      logger.info("[------------開始進入攔截器-------------]");
        // 獲取被攔截的目標全類名
        String className = pjp.getTarget().getClass().getName();
        // 獲取當前正在使用的方法
        String name = pjp.getSignature().getName();
        // 獲取目標類
        Class<?> clazz = Class.forName(className);
        // 增強類所有的方法
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            // 當前遍歷到的方法與正在使用的方法一樣
            if (method.getName().equals(name)) {
                // 獲取當前方法上的登錄註解
                LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
                if (loginRequired!=null) {
                    logger.info("[------------開始進行攔截-------------]");
                    // 獲取請求頭裏面的信息
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                   
                  	/*登錄業務邏輯驗證*/
                  	/*登錄業務邏輯驗證*/
                  	/*登錄業務邏輯驗證*/
                  	
                    logger.info("登錄驗證成功,登錄攔截到的方法:{}",name);
                    return pjp.proceed();
                }
            }
        }

        logger.info("未使用@LoginRequired進行登錄驗證,方法爲:{}",name);
        return  pjp.proceed();

    }
}

4,在Controller層使用@LoginRequire註解即可進行登錄驗證

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章