拦截器和过滤器的区别
2016-01-29 14:34 tony4geek 阅读(1532) 评论(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