1.声明权限注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authentication {
String[] value() default "";
}
2.创建拦截器
public class AuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
//获取自定义注解的值
GetMapping methodAnnotation = handlerMethod.getMethodAnnotation(GetMapping.class);
String[] value = methodAnnotation.value();
//自己的业务逻辑处理
{
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
3.注册拦截器,并设置拦截器路径
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public HandlerInterceptor authenticationInterceptor() {
//注册拦截器
return new AuthenticationInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截所有HTTP请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**");
}
}