欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot中使用springmvc的拦截器-HandlerInterceptorAdapter 博客分类: java springboot 

程序员文章站 2024-02-12 22:15:34
...
springboot中使用springmvc的拦截器-HandlerInterceptorAdapter

拦截器配合注解使用: 权限判断

(1)controller层:
@AuthorityValid(validate=true)
@RequestMapping("/")
public String list(Model model) {
System.out.println(" *** controller *** "+this);
return "index";
}

(2)自定义注解@AuthorityValid
@Documented
@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthorityValid {
    boolean validate() default true;
}

(3)拦截器:会拦截带@AuthorityValid注解的方法
public class AuthorityInterceptorAdapter extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AuthorityInterceptorAdapter.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //处理Permission Annotation,实现方法级权限控制
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
             /*
             * 1、确认当前的controller是否需要进行权限判定,如果需要则进行验证。
             * 2、当controller不需要验证,则验证当前的方法是否需要权限验证,需要则进行验证,不需要则跳出
             * */
            //获取controller注解, controller检查是否需要验证权限控制
            AuthorityValid permission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(AuthorityValid.class);
            if (permission != null && !permission.validate()) { //不需要验证权限
                return super.preHandle(request, response, handler);
            }
             //获取方法注解,方法检查是否需要验证权限控制
            permission = handlerMethod.getMethod().getAnnotation(AuthorityValid.class);
            if (permission != null && !permission.validate()) { //不需要验证权限
            Parameter[] args = handlerMethod.getMethod().getParameters();
            logger.info("参数:{}", args[0]);
            return super.preHandle(request, response, handler);
            }
             // 权限判断,没有权限则跳转至无权限页面,有权限则走正常流程
            logger.info("权限判断...");
        }
        return super.preHandle(request, response, handler);
    }
}

(4)自动配置
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Bean
    public AuthorityInterceptorAdapter getValidInterceptor() {
        return new AuthorityInterceptorAdapter();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getValidInterceptor());
        // 排除配置
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/login**");
        // 拦截配置
        addInterceptor.addPathPatterns("/**");
    }
}

相关标签: springboot