In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what's the difference between filter and interceptor". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "what's the difference between filter and interceptor"?
The use of Filter
First, to use Filter, you must implement the javax.servlet.Filter interface:
The public interface Filter {/ / web application is loaded into the container. After the Filter object is created, the init method initialization is performed to load the resource, only once. Public default void init (FilterConfig filterConfig) throws ServletException {} / / each time a request or response is intercepted, it can be executed multiple times. Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException; / / web application removes the container, and the server is shut down normally, then the destroy method is executed to release resources, only once. Public default void destroy () {}}
Init and destroy are default methods, and the implementation class can be implemented without implementation.
DoFilter must be implemented, that is, as a filter, doFilter must be defined.
The FilterChain object passed in the doFlilter method is used to call the next filter.
The use of interceptors
Public interface HandlerInterceptor {/ / intercepts the execution of handler-- > after HanlerMapping decides the appropriate handler, [before HandlerAdater calls handler.] Default boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true } / / intercept the execution of handler-- > [after HandlerAdapter calls handler], execute default void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, @ Nullable ModelAndView modelAndView) throws Exception {} / / after rendering the view before DispatcherServlet renders the view, and only the preHandle result is true Default void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, @ Nullable Exception ex) throws Exception {}} / / DispatcherServlet if (! mappedHandler.applyPreHandle (processedRequest, response)) {return will be called. / / iterate through all interceptors, call the preHandle method, and proceed only if true is returned. / / that is, processing Contrller mv = ha.handle (processedRequest, response, mappedHandler.getHandler ()); / / View rendering applyDefaultViewName (processedRequest, mv); / / call mappedHandler.applyPostHandle (processedRequest, response, mv) after view rendering.
What's the difference between a filter and an interceptor?
First, the realization principle is different.
The implementation of filter is based on callback function
The interceptor is implemented based on Java's reflection mechanism [dynamic proxy].
Second, the scope of use is different
Filter is the specification of Servlet, which needs to implement javax.servlet.Filter interface, and the use of Filter depends on containers such as Tomcat.
Interceptor is a Spring component, defined under the org.springframework.web.servlet package, managed by the Spring container (there are richer cycle processing methods, fine-grained, and can use resources in Spring), and do not rely on containers such as Tomcat.
Third, the trigger time is different.
This paragraph can be found in the comments of the HandlerInterceptor class that the timing of the trigger is different:
Filter: the request is processed before or after entering the Servlet.
Interceptor: the request is processed before and after the handler [Controller].
4. Different order of execution
Situations where both filters and interceptors are configured:
MyFilter2 before MyFilter1 MyInterceptor1 executes MyInterceptor2 before Controller executes controller method execution before Controller. After MyInterceptor2 Controller, before view rendering, after MyInterceptor1 Controller, before view rendering, after MyInterceptor2 view rendering is completed, after performing MyInterceptor1 view rendering, after performing MyFilter2, after MyFilter1
Order of filters
The chain object is passed in each time to achieve the effect of the final API callback:
Sequence of interceptors
PreHandle1-> preHande2-> [Controller]-> postHandle2-> postHandle1-> afterCompletion2-> afterComplention1preHandle in the order of registration, and the last two are in reverse order.
If the preHandle of an interceptor is false, then all subsequent interceptors will not be executed.
If the preHandle of an interceptor is true, the triggerAfterCompletion of the interceptor must be executed.
PostHandle executes only if all interceptors preHandler are true, that is, normal execution.
Boolean applyPreHandle (HttpServletRequest request, HttpServletResponse response) throws Exception {HandlerInterceptor [] interceptors = getInterceptors (); if (! ObjectUtils.isEmpty (interceptors)) {for (int I = 0; I)
< interceptors.length; i++) { HandlerInterceptor interceptor = interceptors[i]; //一旦当前拦截器preHandle的返回值为false,那么从上一个可用的拦截器的afterCompletion开始 if (!interceptor.preHandle(request, response, this.handler)) { triggerAfterCompletion(request, response, null); return false; //这里返回false意为 后续不进行下去了。 } this.interceptorIndex = i;//interceptorIndex初始化为-1,只有当前拦截器preHandle为true,才会赋值当前的i。 } } return true; }void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv) throws Exception { HandlerInterceptor[] interceptors = getInterceptors(); if (!ObjectUtils.isEmpty(interceptors)) { for (int i = interceptors.length - 1; i >= 0; iMel -) {HandlerInterceptor interceptor = interceptors [I]; interceptor.postHandle (request, response, this.handler, mv);} void triggerAfterCompletion (HttpServletRequest request, HttpServletResponse response, @ Nullable Exception ex) throws Exception {HandlerInterceptor [] interceptors = getInterceptors (); for (int I = this.interceptorIndex; I > = 0; iMel -)}
5. Different ways of controlling the order of execution
Both use the registration order by default, and if you want to control the order of execution, the way is slightly different:
If the filter wants to force the change, you can use the @ Order annotation.
If the interceptor uses the order () method
@ Order (2) @ Component public class MyFilter1 implements Filter {} @ Component public class WebAdapter implements WebMvcConfigurer {@ Autowired MyInterceptor1 myInterceptor1; @ Autowired MyInterceptor2 myInterceptor2; @ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (myInterceptor1) .addPathPatterns ("/ * *") .order (2); registry.addInterceptor (myInterceptor2) .addPathPatterns ("/ * *") .order (1) }} Thank you for your reading. the above is the content of "what's the difference between a filter and an interceptor". After the study of this article, I believe you have a deeper understanding of the difference between a filter and an interceptor. the specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.