自定义注解的实现
1.AOP实现场景 https://zhuanlan.zhihu.com/p/96597358
2.拦截器使用场景[SpringBoot之HandlerInterceptor拦截器]:
通常是权限注解做一些预处理
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface TESTPermit {
PermitEnum[] values() default {PermitEnum.COMMON};
}
---------------------
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
/**
* 请求拦截.
*/
@Slf4j
public class TESTPermitInterceptor implements HandlerInterceptor {
// 在业务处理器处理请求之前被调用
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//优化.
String token = request.getHeader(JwtSecurityDefines.HEADER_AUTHORIZATION);
Integer platId = 0;
//但凡能进入本拦截器的,没token的说明在白名单里,直接放行
if(StringUtil.isNotEmpty(token)){
try {
platId = JwtUtil.***(token);
} catch (Exception ex) {
throw new ****("无权限");
}
}else{
return true;
}
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handlerMethod.hasMethodAnnotation(ATGPermit.class)) {
PermitEnum[] permitEnums = handlerMethod.getMethodAnnotation(ATGPermit.class).values();
List<PermitEnum> permitList = Arrays.asList(permitEnums);
if (permitList.contains(PermitEnum.COMMON)) {
return true;
}
if ((platId == * && permitList.contains(PermitEnum.DMP))
|| (platId == * && permitList.contains(PermitEnum.PSP))) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return true;
}
}
// 在业务处理器处理请求完成之后,生成视图之前执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
// 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
希望写博是我人生坚持在做的事情之一。