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注解,即可是实现登录验证

  • 相关阅读:
    shutil使用
    python解压压缩包
    python配置主机名
    ansible加速不管用
    重启sshd服务
    shell脚本安装python、pip-----非交互式的--批量执行函数
    查看日志
    etcd安全集群三节点扩容至四个节点
    ssh免密登录
    行为型模式之状态模式
  • 原文地址:https://www.cnblogs.com/zjting/p/10880955.html
Copyright © 2011-2022 走看看