spring中过滤器与拦截器的区别
拦截器
- 原理:拦截器是基于java反射机制(动态代理)实现
使用:
实现HandlerInterceptor接口
- preHandle:返回值:boolean表示是否需要将当前的请求拦截下来。方法中Object对象标识的是被拦截的请求的目标对象 - postHandle:在DispatcherServlet进行视图返回渲染之前被调用 - afterCompletion:在DispatcherServlet渲染了对应的视图之后执行,这个方法的主要作用是用于进行资源清理的工作
具体代码
/** * 注册拦截器 */ @SpringBootConfiguration public class WebConfig implements WebMvcConfigurer { @Autowired DataInterceptor dataInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //拦截路径,表示此路径下的所有地址都会先执行此拦截器,通过之后才能访问Controller String[] addPathPatterns = { "/api/**" }; registry.addInterceptor(dataInterceptor).addPathPatterns(addPathPatterns); } } /** * 新建拦截器 */ @Component(value = "dataInterceptor") public class DataInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Systemt.out.println("新建拦截器"); return true; } }
实现WebRequestInterceptor接口
- preHandle方法无返回值 - postHandle - afterCompletion
使用场景
- 使用原则:处理所有请求的共同问题(乱码问题,权限验证问题)
过滤器
- 原理:过滤器是基于函数回调来实现
使用:实现Filter接口
具体代码
/** * 通过过滤器实现跨域处理 */ @Order(1) @Component @WebFilter(urlPatterns = { "/api/*"}, filterName = "corsFilter") public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "authorization, authorizationToken, appCode, x-requested-with, Content-Type, Access-Token"); response.setHeader("Access-Control-Expose-Headers", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() {} }
- 使用场景:设置字符编码,URL级别的权限访问控制,过滤敏感词汇,压缩响应信息
过滤器与拦截器两者对比总结
- 过滤器Filter依赖于Servlet容器,基于回调函数,过滤范围大,还能进行资源过滤
- 拦截器Interceptor依赖于框架容器,基于反射机制,只过滤请求
- tomcat容器中执行顺序: Filter -> Servlet -> Interceptor -> Controller
参考文献
相关推荐
凯哥Java 2020-07-04
smalllove 2020-03-27
HappyHeng 2020-02-01
melonjj 2020-01-04
smalllove 2019-12-21
秦怀卓 2019-11-12
Julywhj 2019-10-22
meleto 2019-09-07
burning 2019-01-25
industry0 2018-09-06
秦怀卓 2018-08-09
MayMatrix 2019-01-25
mowengaoboa 2018-08-09
HappyHeng 2017-01-03
binggege 2016-03-18
Julywhj 2015-06-24