Filters vs. interceptors

One, the same

  1. Are all AOP ideas
  2. Some functions can be implemented both, such as logging, login authentication

Two, different


  1. 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.

  2. Implementation Principle
    Filter is implemented by function callback:
    ApplicationFilterChain.doFilter->internalDoFilter->user-defined filter.doFilter->user-defined filter callback ApplicationFilterChain.doFilter
    Insert picture description here
    Interceptor is implemented based on Java's reflection mechanism (dynamic proxy);
    Proxy .newProxyInstance

  3. Trigger timing
    Insert picture description here
    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.

  4. Interceptors only work on Action, filters can work on all requests

  5. The interceptor can access the objects in the Action context and value stack, but the filter cannot

  6. 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

  1. https://www.cnblogs.com/austinspark-jessylu/p/7453302.html
  2. https://www.toutiao.com/i6834310440495874563/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1597817408&app=news_article&utm_source=weixin&utm_medium=toutiao_ios&use_new_style=1&req_id=202008191410080100140470272A1B83E9&group_id=6834310440495874563

Guess you like

Origin blog.csdn.net/hudmhacker/article/details/108101961
Recommended