切面,就是可以在代码执行的时候,在它执行的前面添加一个东西,一般我们用来做登陆拦截器验证以及敏感词的过滤。
他就3个东西,指定切点(要执行的代码),before代码执行前面加东西。after代码后加东西。一般我们只用切点和before。
1.引入相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2.passToken注解(可有可无)
主要是为了让加注解的接口可以访问,比如说登陆和注册
package xxxx
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 不需要做登录验证的加上当前注解
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
3.切面
这里需要写一个返回方法 sendJsonMessage,用于返回信息
package com.dengta.tanzhiwcustomermarket.config;
import com.alibaba.fastjson.JSONObject;
import com.dengta.tanzhiwcustomermarket.tools.RedisUtils;
import com.dengtacj.tanzhiw.common.api.ResultCode;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Aspect
@Configuration
public class ControllerAspect {
private final static Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
// 定义切点Pointcut 自行写入对应的controller包路径
@Pointcut("execution(* com.dengta.tanzhiwcustomermarket.controller.*.*(..))")
public void pointCut() {
}
@Before("execution(* com.dengta.tanzhiwcustomermarket.controller.*.*(..))&&!@annotation(com.dengta.tanzhiwcustomermarket.config.PassToken)")
public void before(JoinPoint joinPoint) throws Throwable {
//获取token
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String accessToken = request.getHeader("authorization");
HttpServletResponse response = requestAttributes.getResponse();
if(accessToken==null){//没有token直接结束
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",500);
jsonObject.put("message","暂未登录或token已经过期");
sendJsonMessage(response,jsonObject);//必须要有这个
return;//放行
}
}
public static void sendJsonMessage(HttpServletResponse response, Object obj) {
try {
response.setContentType("application/json; charset=utf-8");
response.setStatus(200);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(obj.toString().getBytes("UTF-8"));
outputStream.close();
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试结果