zoukankan      html  css  js  c++  java
  • 面向切面@Aspect

    package com.imooc.demo.filter;
    
    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    
    import java.lang.annotation.*;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    @Documented
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public @interface LoginFilter {
    }
    package com.imooc.demo.filter;
    
    import lombok.extern.slf4j.Slf4j;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.security.auth.login.LoginException;
    import javax.servlet.http.HttpServletRequest;
    
    @Aspect
    @Slf4j
    public class LoginFilterAspect {
    
        //自定义切入点
        @Pointcut("@annotation(com.imooc.demo.filter.LoginFilter)")
        private void allMethod(){}
    
        @Before("allMethod()")
        public Object exec(JoinPoint joinPoint) throws Throwable{
    
            try{
                Object[] args = joinPoint.getArgs();
                HttpServletRequest request = null;
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof HttpServletRequest){
                        request = (HttpServletRequest) args[i];
                        break;
                    }
                }
                if (null==request){
                    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
                    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
                    request = sra.getRequest();
                }
    
                //获取用户登录信息
                Object user = request.getSession().getAttribute("user");
    
                if (null == user){
                    log.info("用户未登录。");
                   return new LoginException();
                }
            }catch (Exception ex){
                throw ex;
            }
            return null;
        }
    
    }

    后续在方法上加上@LoginFilter注解,即可是实现登录验证

  • 相关阅读:
    python note 30 断点续传
    python note 29 线程创建
    python note 28 socketserver
    python note 27 粘包
    python note 26 socket
    python note 25 约束
    Sed 用法
    python note 24 反射
    python note 23 组合
    python note 22 面向对象成员
  • 原文地址:https://www.cnblogs.com/zjting/p/10880955.html
Copyright © 2011-2022 走看看