One, the same
- Are all AOP ideas
- Some functions can be implemented both, such as logging, login authentication
Two, different
-
Different from birth Filter comes from the javax.servlet package and must depend on the tomcat environment;
Interceptor comes from the spring family and does not depend on the web container environment such as tomcat. It can be used not only in web programs, but also in applications such as Application and Swing. -
Implementation Principle
Filter is implemented by function callback:
ApplicationFilterChain.doFilter->internalDoFilter->user-defined filter.doFilter->user-defined filter callback ApplicationFilterChain.doFilter
Interceptor is implemented based on Java's reflection mechanism (dynamic proxy);
Proxy .newProxyInstance -
Trigger timing
Filter is after the request enters the container, but before entering the servlet, it is preprocessed, and the request ends after the servlet is processed.
The Interceptor is preprocessed before entering the Controller after the request enters the servlet, and the request ends after the corresponding view is rendered in the Controller. -
Interceptors only work on Action, filters can work on all requests
-
The interceptor can access the objects in the Action context and value stack, but the filter cannot
-
The control execution order is different.
Filter: The filter uses the @Order annotation to control the execution order. The @Order controls the level of the filter. The smaller the value, the higher the level, the first to execute
Interceptor: The default execution order of the interceptor is its registration order, which can also be Manually set the control through Order, the smaller the value, the earlier it will be executed.
Three, reference
- https://www.cnblogs.com/austinspark-jessylu/p/7453302.html
- https://www.toutiao.com/i6834310440495874563/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1×tamp=1597817408&app=news_article&utm_source=weixin&utm_medium=toutiao_ios&use_new_style=1&req_id=202008191410080100140470272A1B83E9&group_id=6834310440495874563