63 lines
1.5 KiB
Java
63 lines
1.5 KiB
Java
package com.imyeyu.spring.annotation;
|
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
import org.springframework.lang.NonNull;
|
|
import org.springframework.web.method.HandlerMethod;
|
|
import org.springframework.web.servlet.HandlerInterceptor;
|
|
|
|
import java.lang.annotation.Annotation;
|
|
|
|
/**
|
|
* 抽象验证令牌
|
|
*
|
|
* @param <A> 注解类型
|
|
* @author 夜雨
|
|
* @version 2021-08-16 18:07
|
|
*/
|
|
public abstract class RequiredTokenAbstractInterceptor<A extends Annotation> implements HandlerInterceptor {
|
|
|
|
private final Class<A> annotation;
|
|
|
|
/**
|
|
* 创建 Token 验证拦截器
|
|
*
|
|
* @param annotation 注解类型
|
|
*/
|
|
public RequiredTokenAbstractInterceptor(Class<A> annotation) {
|
|
this.annotation = annotation;
|
|
}
|
|
|
|
/**
|
|
* 处理前
|
|
*
|
|
* @param req 请求
|
|
* @param resp 返回
|
|
* @param handler 处理方法
|
|
* @return true 为通过
|
|
*/
|
|
@Override
|
|
public boolean preHandle(@NonNull HttpServletRequest req,
|
|
@NonNull HttpServletResponse resp,
|
|
@NonNull Object handler) {
|
|
// 方法注解
|
|
if (handler instanceof HandlerMethod handlerMethod) {
|
|
A requiredTokenAnnotation = handlerMethod.getMethodAnnotation(annotation);
|
|
if (requiredTokenAnnotation == null) {
|
|
return true;
|
|
}
|
|
return beforeRun(req, resp);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 访问前(通过 Token 限制)
|
|
*
|
|
* @param req 请求
|
|
* @param resp 返回
|
|
* @return true 为通过
|
|
*/
|
|
protected abstract boolean beforeRun(HttpServletRequest req, HttpServletResponse resp);
|
|
}
|