过滤器和拦截器的区别

12 篇文章 0 订阅

过滤器和拦截器

Difference:
A Servlet Filter is used in the web layer only, you can’t use it outside of a
web context. Interceptors can be used anywhere. That’s the main difference.

In my opinion one of the biggest difference between Filters and Interceptors is:

Filter works only in J2EE web applications, you can not use outside of the application servers, Interceptors can work in different components and not depends on the web layer, in summary interceptor have a wide field than filters. If you are planning to move some component outside the container, you should consider use interceptors.

Filters work more in the request/response domain, in the other hand interceptor act more in the method execution domain.

If you need to do something that could affect the request or response to your application such as logging, security, audit, or you will affect the data coming on them, your option is filter, don’t forget the plug ability that those provides.

Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events.

  • Filter基于回调函数,我们需要实现的filter接口中doFilter方法就是回调函数,而interceptor则基于java本身的反射机制,这是两者最本质的区别。
  • Filter是依赖于servlet容器的,即只能在servlet容器中执行,很显然没有servlet容器就无法来回调doFilter方法。而interceptor与servlet容器无关。
  • Filter的过滤范围比Interceptor大,Filter除了过滤请求外通过通配符可以保护页面,图片,文件等等,而Interceptor只能过滤请求。
  • Filter的过滤例外一般是在加载的时候在init方法声明,而Interceptor可以通过在xml声明是guest请求还是user请求来辨别是否过滤

####综上所述
一个简单的数据流程,请求过来进入到 Filter pre —>dispatcher—>preHandle–>controller–>postHandle—>afterCompletion—>Filter After

interceptors-or-filters
spring-handlerinterceptor-vs-servlet-filters

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值