拦截器通过自定义注解来判断是否拦截
自定义一个注解,又有拦截器,方法上只要有这个注解,就不进行拦截,放行
1.自定义注解
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthAccess {
}
2.拦截器配置
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*...*/
if(!(handler instanceof HandlerMethod)){
return true;
}else {
HandlerMethod h = (HandlerMethod) handler;
AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
if(authAccess!=null){
return true;
}
}
/*...*/
}
}
3.配置
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/index/**")
.excludePathPatterns("/admin","/admin/login");
}
}
4.controller层使用
@RestController
public class IndexController {
@AuthAccess
@GetMapping("/index")
public Result index(){
return Result.success("index");
}
}