How does spring boot use spring AOP to implement interceptors
- 2020-06-19 10:25:56
- OfStack
In spring boot, a simple step is to use spring AOP to implement 1 interceptor:
1. Introduction of dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2, create interceptor class (defined in the class, the blocking rule: intercept com. xjj. web. controller package all the classes below, an @ RequestMapping annotation methods.) :
/**
* Interceptor: Logs user actions to check if the user is logged in...
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value("${spring.profiles}")
private String env;
/**
* Define interception rules: Intercept com.xjj.web.controller Of all the classes below the package, there are @RequestMapping Method of annotation.
*/
@Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void controllerMethodPointcut(){}
/**
* Specific implementation of the interceptor
* @param pjp
* @return JsonResult (The execution result of the blocked method, or an error message requiring login.)
*/
@Around("controllerMethodPointcut()") // Specify interceptor rules; Or you can just put" execution(* com.xjj.........) "Let me write it here
public Object Interceptor(ProceedingJoinPoint pjp){
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod(); // Gets the method that is intercepted
String methodName = method.getName(); // Gets the name of the method being intercepted
Set<Object> allParams = new LinkedHashSet<>(); // Save all request parameters for output to the log
logger.info(" Request start, Method: {}", methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug("arg: {}", arg);
if (arg instanceof Map<?, ?>) {
// In the extraction method MAP Parameter used for logging
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) arg;
allParams.add(map);
}else if(arg instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) arg;
if(isLoginRequired(method)){
if(!isLogin(request)){
result = new JsonResult(ResultCode.NOT_LOGIN, " This operation requires login! Log in? \n\n Don't know your login account? Please contact Lao Xu. ", null);
}
}
// To obtain query string or posted form data parameter
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap!=null && paramMap.size()>0){
allParams.add(paramMap);
}
}else if(arg instanceof HttpServletResponse){
//do nothing...
}else{
//allParams.add(arg);
}
}
try {
if(result == null){
// 1 Continue execution of the intercepted method if it is normal
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info("exception: ", e);
result = new JsonResult(ResultCode.EXCEPTION, " Exception occurs: "+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info("{} End of request, time consuming: {}ms", methodName, costMs);
}
return result;
}
/**
* judge 1 Whether or not a method requires login
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals("prod")){ // Only production environments require login
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
// Determine if you are logged in
private boolean isLogin(HttpServletRequest request) {
return true;
/*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
if("1".equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
return true;
}else {
return false;
}*/
}
}
3, test,
The browser input: http: / / localhost: 8082 / api admin/login
Test results:
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - Request start, Method: login
2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login End of request, time consuming: 8ms
Verify that the interceptor is in effect.
Source code reference: https: / / github com xujijun/my spring -- boot
Es43EN-ES44en-boot_jb51.rar