目录
拦截器Interceptor
是一种动态拦截方法调用的机制,类似于过滤器。
拦截器是Spring框架中提供的,用来动态拦截控制器方法的执行。
作用
拦截请求,在指定方法调用前后,根据业务需要执行预先设定的代码。
使用步骤
1. 定义拦截器
编写一个登录拦截器类实现HandlerInterceptor接口,并重写其所有方法
注意
preHandle方法:目标资源方法执行前执行。 返回true:放行 返回false:不放行
postHandle方法:目标资源方法执行后执行
afterCompletion方法:视图渲染完毕后执行,最后执行
2. 注册配置拦截器
编写一个配置类实现WebMvcConfigurer接口,@Configuration 添加在类上标明是配置类,并重写addInterceptors方法,再将拦截器通过@Autowired注入该类
通过addPathPatterns("要拦截路径")方法,指定要拦截哪些资源。
调用excludePathPatterns("不拦截路径")方法,指定哪些资源不需要拦截
Interceptor详解
1. 拦截器的拦截路径配置
@Configuration
public class WebConfig implements WebMvcConfigurer {//拦截器对象
@Autowired
private LoginCheckInterceptor loginCheckInterceptor;@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器对象
registry.addInterceptor(loginCheckInterceptor)
.addPathPatterns("/**")//设置拦截器拦截的请求路径( /** 表示拦截所有请求)
.excludePathPatterns("/login");//设置不拦截的请求路径
}
}
/* 一级路径 能匹配/depts,/emps,/login,不能匹配 /depts/1
/** 任意级路径 能匹配/depts,/depts/1,/depts/1/2
/depts/* /depts下的一级路径 能匹配/depts/1,不能匹配/depts/1/2,/depts
/depts/** /depts下的任意级路径 能匹配/depts,/depts/1,/depts/1/2,不能匹配/emps/1
2. 拦截器的执行流程(只拦截Spring中的资源)
preHandle方法->控制层->postHandle方法->afterCompletion方法
过滤器和拦截器之间的区别
- 接口规范不同:过滤器需要实现Filter接口,而拦截器需要实现HandlerInterceptor接口。
- 拦截范围不同:过滤器Filter会拦截所有的资源,而Interceptor只会拦截Spring环境中的资源。