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

一、定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoNeedLogin {
}

二、定义拦截器

@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;
    }
}

三、添加拦截器

@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

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

四、使用

    @ResponseBody
    @GetMapping("needLogin")
    public String needLogin() {
        return "needLogin";
    }

    @NoNeedLogin
    @ResponseBody
    @GetMapping("noNeedLogin")
    public String noNeedLogin() {
        return "noNeedLogin";
    }

发表评论

textsms
account_circle
email

Yuyy

注解+拦截器实现权限控制
一、定义注解 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NoNeedLogin { } 二、定义拦截器 @Component public class AuthenticationInterc…
扫描二维码继续阅读
2021-02-02
友情链接
标签
归档
近期文章