拦截器通过自定义注解来判断是否拦截
自定义一个注解,又有拦截器,方法上只要有这个注解,就不进行拦截,放行
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");
}
}
自定义注解与拦截器实现权限控制
本文介绍了如何通过自定义注解和拦截器实现Spring MVC中的权限控制。首先定义了一个名为`AuthAccess`的注解,标记在需要免拦截的方法上。然后创建了一个拦截器`MyInterceptor`,在预处理方法中检查请求的处理器是否包含该注解,如果存在则放行,否则进行拦截。最后在配置类`WebConfig`中注册了拦截器,并设置拦截路径及排除路径。这种方法允许灵活地控制特定方法的访问权限。

被折叠的 条评论
为什么被折叠?



