• 过滤器和拦截器之间的区别


    过滤器和拦截器之间的区别:

    1. 过滤器初始化在拦截器之前,在IOC容器bean节点初始化之后。
    2. 在一个请求生命周期中过滤器只被调用一次,拦截器可被调用多次。
    3. 过滤器在项目启动时初始化一次,拦截器是通过bean节点初始化在容器中。

    创建项目对比拦截器与过滤器区别:

    过滤器:

     1 /**
     2  * @filename MyFilter.Java
     3  * @desc 过滤器测试
     4  * @blog http://www.cnblogs.com/goodcheap
     5  * @author Chinda Wang
     6  * @create 2018-01-02 7:45
     7  * @version v1.0
     8  * @copyright Copyright © 2017 达华信息科技有限公司 版权所有
     9  * @modifyhistory 2018-01-02 7:45
    10  * @modifyauthor Chinda Wang
    11  * @modifydesc
    12  */
    13 package com.itdoc.filter;
    14 
    15 import com.itdoc.service.MyService;
    16 import org.springframework.beans.factory.annotation.Autowired;
    17 import org.springframework.stereotype.Component;
    18 
    19 import javax.servlet.*;
    20 import java.io.IOException;
    21 
    22 
    23 /**
    24  * @desc 过滤器测试
    25  * @author Chinda Wang
    26  * @create 2018-01-02 7:45
    27  */
    28 @Component
    29 public class MyFilter implements Filter {
    30 
    31     @Autowired
    32     private MyService myService;
    33 
    34     /**
    35      * Filter 初始化
    36      * @param filterConfig
    37      * @throws ServletException
    38      */
    39     @Override
    40     public void init(FilterConfig filterConfig) throws ServletException {
    41         System.out.println("初始化Filter!!!");
    42         myService.getFilterInit();
    43     }
    44 
    45     @Override
    46     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    47         System.out.println("Filter doFilter方法!!!");
    48         System.out.println("Filter调用chain.doFilter方法之前!!!");
    49         myService.getFilterDoFilter("之前");
    50         chain.doFilter(request, response);
    51         myService.getFilterDoFilter("之后");
    52         System.out.println("Filter调用chain.doFilter方法之后!!!");
    53     }
    54 
    55     @Override
    56     public void destroy() {
    57         System.out.println("销毁Filter!!");
    58         myService.getFilterDestroy();
    59     }
    60 }
    过滤器

    拦截器:

     1 /**
     2  * @filename MyItercepter.Java
     3  * @desc 拦截器测试
     4  * @blog http://www.cnblogs.com/goodcheap
     5  * @author Chinda Wang
     6  * @create 2018-01-02 7:46
     7  * @version v1.0
     8  * @copyright Copyright © 2017 达华信息科技有限公司 版权所有
     9  * @modifyhistory 2018-01-02 7:46
    10  * @modifyauthor Chinda Wang
    11  * @modifydesc
    12  */
    13 package com.itdoc.intercepter;
    14 
    15 import com.itdoc.service.MyService;
    16 import org.springframework.beans.factory.annotation.Autowired;
    17 import org.springframework.stereotype.Component;
    18 import org.springframework.web.servlet.HandlerInterceptor;
    19 import org.springframework.web.servlet.ModelAndView;
    20 
    21 import javax.servlet.http.HttpServletRequest;
    22 import javax.servlet.http.HttpServletResponse;
    23 
    24 /**
    25  * @desc 拦截器测试
    26  * @author Chinda Wang
    27  * @create 2018-01-02 7:46
    28  */
    29 @Component
    30 public class MyItercepter implements HandlerInterceptor {
    31 
    32     @Autowired
    33     private MyService myService;
    34 
    35     /**
    36      * 在调用 Controller 之前调用
    37      * @param request
    38      * @param response
    39      * @param obj
    40      * @return true 表示继续流程(调用下一个拦截器或处理器) false 表示中断流程, 不在调用其它拦截器或处理器, 需要通过 response 来响应。
    41      * @throws Exception
    42      */
    43     @Override
    44     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
    45         System.out.println("第一个拦截器调用 preHandler方法!!!");
    46         myService.preHandle();
    47         return true;
    48     }
    49 
    50     /**
    51      * 在Controller调用之后, DispatcherServlet返回渲染视图之前被调用, 可操作ModelAndView对象对试图进行渲染操作。
    52      * 注意: ModelAndView对象有可能为null
    53      * @param request
    54      * @param response
    55      * @param obj
    56      * @param modelAndView
    57      * @throws Exception
    58      */
    59     @Override
    60     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelAndView) throws Exception {
    61         System.out.println("第一个拦截器调用 postHandle方法!!!");
    62         myService.postHandle();
    63     }
    64 
    65     /**
    66      * 在视图渲染完毕后调用
    67      * @param request
    68      * @param response
    69      * @param obj
    70      * @param e
    71      * @throws Exception
    72      */
    73     @Override
    74     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception {
    75         System.out.println("第一个拦截器调用 afterCompletion方法!!!");
    76         myService.afterCompletion();
    77     }
    78 }
    拦截器1
     1 /**
     2  * @filename MyIntercepterScond.Java
     3  * @desc 我的第二个拦截器
     4  * @blog http://www.cnblogs.com/goodcheap
     5  * @author Chinda Wang
     6  * @create 2018-01-02 10:16
     7  * @version v1.0
     8  * @copyright Copyright © 2017 达华信息科技有限公司 版权所有
     9  * @modifyhistory 2018-01-02 10:16
    10  * @modifyauthor Chinda Wang
    11  * @modifydesc
    12  */
    13 package com.itdoc.intercepter;
    14 
    15 import org.springframework.stereotype.Component;
    16 import org.springframework.web.servlet.HandlerInterceptor;
    17 import org.springframework.web.servlet.ModelAndView;
    18 
    19 import javax.servlet.http.HttpServletRequest;
    20 import javax.servlet.http.HttpServletResponse;
    21 
    22 /**
    23  * @desc 我的第二个拦截器
    24  * @author Chinda Wang
    25  * @create 2018-01-02 10:16
    26  */
    27 @Component
    28 public class MyIntercepterScond implements HandlerInterceptor {
    29     @Override
    30     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
    31         System.out.println("第二个拦截器调用 preHandle方法!!!");
    32         return true;
    33     }
    34 
    35     @Override
    36     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelAndView) throws Exception {
    37         System.out.println("第二个拦截器调用 postHandle方法!!!");
    38     }
    39 
    40     @Override
    41     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception {
    42         System.out.println("第二个拦截器调用 afterCompletion方法!!!");
    43     }
    44 }
    拦截器2

    注册配置拦截器:

     1 /**
     2  * @filename MyIntercepterConfig.Java
     3  * @desc
     4  * @blog http://www.cnblogs.com/goodcheap
     5  * @author Chinda Wang
     6  * @create 2018-01-02 8:33
     7  * @version v1.0
     8  * @copyright Copyright © 2017 达华信息科技有限公司 版权所有
     9  * @modifyhistory 2018-01-02 8:33
    10  * @modifyauthor Chinda Wang
    11  * @modifydesc
    12  */
    13 package com.itdoc.configuration;
    14 
    15 import com.itdoc.intercepter.MyIntercepterScond;
    16 import com.itdoc.intercepter.MyItercepter;
    17 import org.springframework.beans.factory.annotation.Autowired;
    18 import org.springframework.stereotype.Component;
    19 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    20 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    21 
    22 /**
    23  * @desc
    24  * @author Chinda Wang
    25  * @create 2018-01-02 8:33
    26  */
    27 @Component
    28 public class MyIntercepterConfig extends WebMvcConfigurerAdapter {
    29 
    30     @Autowired
    31     private MyItercepter myItercepter;
    32 
    33     @Autowired
    34     private MyIntercepterScond myIntercepterScond;
    35 
    36     /**
    37      * 在容器中注册拦截器, 定义拦截器拦截所针对的 uri
    38      * @param registry
    39      */
    40     @Override
    41     public void addInterceptors(InterceptorRegistry registry) {
    42         registry.addInterceptor(myItercepter).addPathPatterns("/**");
    43         registry.addInterceptor(myIntercepterScond).addPathPatterns("/**");
    44         super.addInterceptors(registry);
    45     }
    46 }
    注册配置拦截器

    项目启动控制台输出:

    . ____ _ __ _ _
    /\ / ___'_ __ _ _(_)_ __ __ _
    ( ( )\___ | '_ | '_| | '_ / _` |
    \/ ___)| |_)| | | | | || (_| | ) ) ) )
    ' |____| .__|_| |_|_| |_\__, | / / / /
    =========|_|==============|___/=/_/_/_/
    :: Spring Boot :: (v1.5.9.RELEASE)

    2018-01-02 11:10:51.360 INFO 9780 --- [ main] c.itdoc.FilteritercepterdiffApplication : Starting FilteritercepterdiffApplication on Mr_King-PC with PID 9780 (E:LearnfiterItercepterfilteritercepterdiff argetclasses started by Mr_King in E:LearnfiterItercepterfilteritercepterdiff)
    2018-01-02 11:10:51.364 INFO 9780 --- [ main] c.itdoc.FilteritercepterdiffApplication : No active profile set, falling back to default profiles: default
    2018-01-02 11:10:51.452 INFO 9780 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@82de64a: startup date [Tue Jan 02 11:10:51 CST 2018]; root of context hierarchy
    2018-01-02 11:10:53.496 INFO 9780 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
    2018-01-02 11:10:53.507 INFO 9780 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
    2018-01-02 11:10:53.508 INFO 9780 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
    2018-01-02 11:10:53.609 INFO 9780 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
    2018-01-02 11:10:53.610 INFO 9780 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2162 ms
    2018-01-02 11:10:53.779 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
    2018-01-02 11:10:53.784 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-01-02 11:10:53.785 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-01-02 11:10:53.785 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-01-02 11:10:53.785 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
    2018-01-02 11:10:53.785 INFO 9780 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'myFilter' to: [/*]
    初始化Filter!!!
    Filter 初始化中调用 MyService 中 getFilterInit 方法!!!
    2018-01-02 11:10:54.130 INFO 9780 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@82de64a: startup date [Tue Jan 02 11:10:51 CST 2018]; root of context hierarchy
    2018-01-02 11:10:54.194 INFO 9780 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hi]}" onto public java.lang.String com.itdoc.controller.MyController.helloWorld()
    2018-01-02 11:10:54.202 INFO 9780 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2018-01-02 11:10:54.202 INFO 9780 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2018-01-02 11:10:54.241 INFO 9780 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-01-02 11:10:54.242 INFO 9780 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-01-02 11:10:54.281 INFO 9780 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-01-02 11:10:54.506 INFO 9780 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
    2018-01-02 11:10:54.560 INFO 9780 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    2018-01-02 11:10:54.565 INFO 9780 --- [ main] c.itdoc.FilteritercepterdiffApplication : Started FilteritercepterdiffApplication in 3.647 seconds (JVM running for 4.254)

    请求调用后控制台输出:

    2018-01-02 11:12:27.397 INFO 9780 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
    2018-01-02 11:12:27.397 INFO 9780 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
    2018-01-02 11:12:27.415 INFO 9780 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms
    Filter doFilter方法!!!
    Filter调用chain.doFilter方法之前!!!
    Filter doFilter 方法中调用 MyService 中 getFilterDoFilter 方法!!!在调用chain.doFilter方法之前
    第一个拦截器调用 preHandler方法!!!
    第一个拦截器调用 MyService 中 preHandle方法!!!
    第二个拦截器调用 preHandle方法!!!
    第二个拦截器调用 postHandle方法!!!
    第一个拦截器调用 postHandle方法!!!
    第一个拦截器调用 MyService 中 postHandle方法!!!
    第二个拦截器调用 afterCompletion方法!!!
    第一个拦截器调用 afterCompletion方法!!!
    第一个拦截器调用 MyService 中 afterCompletion方法!!!
    Filter doFilter 方法中调用 MyService 中 getFilterDoFilter 方法!!!在调用chain.doFilter方法之后
    Filter调用chain.doFilter方法之后!!!

    流程图:

    git源码 :https://github.com/wcd19901010/learnRepository/tree/master/filteritercepterdiff

  • 相关阅读:
    第一阶段冲刺第二天
    第一阶段冲刺第一天
    用户场景描述
    第十一周总结
    第十周总结
    找水王
    sqli-labs第5关布尔盲注pyhton脚本
    intel:spectre&Meltdown侧信道攻击(一)
    windows:shellcode 远程线程hook/注入(五)
    windows:shellcode 远程线程hook/注入(四)
  • 原文地址:https://www.cnblogs.com/chinda/p/8176250.html
Copyright © 2020-2023  润新知