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註解即可進行登錄驗證