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

  • 相关阅读:
    【安卓5】高级控件——ListActivity
    【安卓5】高级控件——滚动视图、列表视图[ListView、SimpleAdapter类]
    时序图(组成元素)
    【安卓5】高级控件——拖动条SeekBar
    【安卓5】高级控件——对话框操作事件
    【安卓5】高级控件——信息提示框、对话框
    【安卓4】事件处理——键盘事件、触摸事件
    小综合实例
    相对路径的问题
    什么时候修改class
  • 原文地址:https://www.cnblogs.com/zjting/p/10880955.html
Copyright © 2020-2023  润新知