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;
@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注解即可进行登录验证