博客登录实现权限拦截

HandlerInterceptor(处理器拦截器)

public interface HandlerInterceptor {

    // 在执行目标方法之前执行
    boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception;

    // 执行目标方法之后执行
    void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;

    // 在请求已经返回之后执行
    void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;

}

HandlerInterceptor的三种方法,属于方法拦截器



先讲怎么实现吧

首先 创建一个配置类,这里要用到@Configuration这个注解,

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter{

    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/**");
    }
}
这样就相当于配置了拦截器,复写 addInterceptors,服务器启动,自动调用这个方法,我们直接new一个自定义拦截器, 注册到整个拦截链中, 并且制定拦截路径, 这样当满足请求url拦截配置时, 我们的自定义拦截器就会执行相应的方法了.


第二步自定义一个注解类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Access {

    String[] value() default {};

    String[] authorities() default {};

    String[] roles() default {};

}

第三步是编写拦截器的逻辑

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    //在调用方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //将Handler强转为HandlerMethod
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //从方法处理器中获取出要调用的方法
        Method method = handlerMethod.getMethod();
        //获取方法上的Access注解
        Access access = method.getAnnotation(Access.class);
        if (access == null) {
            return true;
        }
        if (access.authorities().length > 0) {
            //如果权限配置不为空,则取出配置
            String[] authorities = access.authorities();
            Set<String> authSet = new HashSet<>();
            for (String authory : authorities) {
                //将权限加入一个set集合中
                authSet.add(authory);
            }
            String role= (String) httpServletRequest.getSession().getAttribute("role");
            if (!RegExpUtil.isNull(role)) {
                if (authSet.contains(role)) {
                    return true;
                }
            }
        }


        return false;
    }

}

继承HandlerInterceptorAdapter,实现preHandle这个方法

然后我这里使用的是登录存session,然后在拦截器中比较,

匹配就放行


本文拦截器参考http://www.jianshu.com/p/43c97352aa1e实现



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值