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实现