1.在pom.xml中添加配置
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.10</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.10</version> </dependency>
2.新建拦截类LoginIntercept.java
package com.llltony.springboot.controller; import com.llltony.springboot.bean.Employee; import com.llltony.springboot.bean.ResultMap; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpSession; //AOP做登录拦截 @Component @Aspect public class LoginIntercept { private static final Logger logger = LoggerFactory.getLogger(LoginIntercept.class); @Pointcut("within(com.llltony.springboot.controller..*) && !within(com.llltony.springboot.controller.LoginController)") public void pointCut() { } @Around("pointCut()") public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable { HttpSession session= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(); Employee user = (Employee) session.getAttribute("userInfo"); String userRole = (String) session.getAttribute("userRole"); ResultMap obj= new ResultMap(); if(user == null) { logger.info("-------------没有登录-------------"); obj.setMessage("未登录"); obj.setStatus("500"); return obj; } return pjp.proceed(); } }
3.结果bean类
package com.llltony.springboot.bean; public class ResultMap { String message; String status; public String getMessage() { return message; } public String getStatus() { return status; } public void setMessage(String message) { this.message = message; } public void setStatus(String status) { this.status = status; } }