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