实现功能:对某个目录下所有请求接口进行拦截判断,如检测登录状态等。
需要pom.xml引入aop:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
具体实现:
package com.tuijie.gainguest.common.aspect; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; //import com.tuijie.gainguest.common.enums.JsonCodeEnum; //import com.tuijie.gainguest.common.result.JsonResp; //import com.tuijie.gainguest.controller.Constants; import lombok.extern.slf4j.Slf4j; 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.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; /** * @Author: admin * @Description: 切面AOP * @Date Created in 9:39 AM 2020/3/31 * @Modified By: */ @Aspect @Component @Slf4j //log日志,可选 public class SysPointcut { // 放行接口 private final static String[] excludePathPatterns = { "/api/sysUserAdmin/login", "/api/sysUserAdmin/logout", }; private static final SerializerFeature[] serializerFeatures; static { serializerFeatures = new SerializerFeature[] { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty }; } /** * 后台管理切面AOP * 定义切入点,切入点为com.tuijie.gainguest.controller.admin包下所有类-接口 * 通过@Pointcut注解声明频繁使用的切点表达式 */ @Pointcut("execution(* com.tuijie.gainguest.controller.admin..*.*(..)))") public void BrokerAspect() {} @Around("BrokerAspect()") public Object beforeExec(ProceedingJoinPoint pjp) throws Throwable { //获取request信息 RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; assert sra != null; HttpServletRequest request = sra.getRequest(); HttpSession session = request.getSession(); String uri = request.getRequestURI(); if (!Arrays.asList(excludePathPatterns).contains(uri)) { Object admin = session.getAttribute(/*Constants.ACCOUNT_SESSION*/"test"); // JsonResp jsonResp; if (admin == null) { log.warn("未登录: [{}] [{}]", session.getId(), uri); // jsonResp = JsonResp.fail(JsonCodeEnum.OVERTIME.getMessage(), JsonCodeEnum.OVERTIME.getCode()); HttpServletResponse response = sra.getResponse(); assert response != null; response.setCharacterEncoding("utf-8"); response.setContentType("application/json; charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(JSON.toJSONString(/*jsonResp*/new HashMap<String, Object>(){{put("id", 1);}}, serializerFeatures)); writer.flush(); writer.close(); return null; } } return pjp.proceed(); } }