首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >注解+拦截器实现权限控制

注解+拦截器实现权限控制

作者头像
Yuyy
发布于 2022-09-21 09:49:25
发布于 2022-09-21 09:49:25
6350
举报

本文最后更新于 511 天前,其中的信息可能已经有所发展或是发生改变。

一、定义注解

代码语言:javascript
复制
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoNeedLogin {
}

二、定义拦截器

代码语言:javascript
复制
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isHandlerMethod = handler instanceof HandlerMethod;
        if (!isHandlerMethod) {
            return true;
        }
        boolean isNoNeedLogin = ((HandlerMethod) handler).getMethodAnnotation(NoNeedLogin.class)!=null;
        if (isNoNeedLogin) {
            return true;
        }
        return false;
    }
}

三、添加拦截器

代码语言:javascript
复制
@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor);
    }
}

四、使用

代码语言:javascript
复制
    @ResponseBody
    @GetMapping("needLogin")
    public String needLogin() {
        return "needLogin";
    }

    @NoNeedLogin
    @ResponseBody
    @GetMapping("noNeedLogin")
    public String noNeedLogin() {
        return "noNeedLogin";
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-2-02 1,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 一、定义注解
  • 二、定义拦截器
  • 三、添加拦截器
  • 四、使用
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档