@Configuration
public class myFilter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器");
if (!(handler instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Class<?> beanType = handlerMethod.getBeanType();
Method method = handlerMethod.getMethod();
MyAnnotation myAnnotation =null;
if (beanType.isAnnotationPresent(MyAnnotation.class)){
myAnnotation = beanType.getAnnotation(MyAnnotation.class);
}else if (method.isAnnotationPresent(MyAnnotation.class)){
myAnnotation = method.getAnnotation(MyAnnotation.class);
}
if (Objects.isNull(myAnnotation)){
return true;
}
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if (user==null){
throw new Exception ("访问失败,您没有权限访问!");
}else {
return true;
}
}
}
@Configuration
public class InterceptorTrainConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new myFilter()).addPathPatterns("/**");
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String name() default "";
}