zoukankan      html  css  js  c++  java
  • springboot中filter的配置和顺序执行

    项目结构


    springboot版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    Filter代码

    AFilter

    package com.wang.sb.filter;
    import javax.servlet.*;
    import java.io.IOException;
    
    /**
     * @Author wly
     * @Date 2018/6/14 10:54
     */
    public class AFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("I'm AFilter");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

     BFilter

    package com.wang.sb.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    /**
     * @Author wly
     * @Date 2018/6/14 10:54
     */
    public class BFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("I'm BFilter");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

      CFilter

    package com.wang.sb.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    /**
     * @Author wly
     * @Date 2018/6/14 10:54
     */
    public class CFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("I'm CFilter");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

      DFilter

    package com.wang.sb.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    /**
     * @Author wly
     * @Date 2018/6/14 10:54
     */
    public class DFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("I'm DFilter");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

     EFilter

    package com.wang.sb.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    /**
     * @Author wly
     * @Date 2018/6/14 10:54
     */
    public class EFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("I'm EFilter");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

    Filter配置:名称、拦截位置、执行顺序等

     
    package com.wang.sb.config;

    import com.wang.sb.filter.*;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    import java.util.ArrayList;
    import java.util.List;

    /**
    * @Description
    * @Author wly
    * @Date 2018/6/14 14:20
    */
    @Configuration
    public class FilterConfig {
    @Bean
    public FilterRegistrationBean buildAFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setOrder(6);
    filterRegistrationBean.setFilter(new AFilter());
    filterRegistrationBean.setName("filter1");
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean buildBFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setOrder(2);
    filterRegistrationBean.setFilter(new BFilter());
    filterRegistrationBean.setName("filter2");
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean buildCFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setOrder(3);
    filterRegistrationBean.setFilter(new CFilter());
    filterRegistrationBean.setName("filter3");
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean buildDFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setOrder(4);
    filterRegistrationBean.setFilter(new DFilter());
    filterRegistrationBean.setName("filter4");
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean buildEFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setOrder(5);
    filterRegistrationBean.setFilter(new EFilter());
    filterRegistrationBean.setName("filter5");
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
    }

    }
    
    


    控制台日志(启动服务加载了filter)

    "D:dev toolsjdkjdk8injava" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:59538,suspend=y,server=n -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=59537 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath "D:dev toolsjdkjdk8jrelibcharsets.jar;D:dev toolsjdkjdk8jrelibdeploy.jar;D:dev toolsjdkjdk8jrelibextaccess-bridge-64.jar;D:dev toolsjdkjdk8jrelibextcldrdata.jar;D:dev toolsjdkjdk8jrelibextdnsns.jar;D:dev toolsjdkjdk8jrelibextjaccess.jar;D:dev toolsjdkjdk8jrelibextjfxrt.jar;D:dev toolsjdkjdk8jrelibextlocaledata.jar;D:dev toolsjdkjdk8jrelibext
    ashorn.jar;D:dev toolsjdkjdk8jrelibextsunec.jar;D:dev toolsjdkjdk8jrelibextsunjce_provider.jar;D:dev toolsjdkjdk8jrelibextsunmscapi.jar;D:dev toolsjdkjdk8jrelibextsunpkcs11.jar;D:dev toolsjdkjdk8jrelibextzipfs.jar;D:dev toolsjdkjdk8jrelibjavaws.jar;D:dev toolsjdkjdk8jrelibjce.jar;D:dev toolsjdkjdk8jrelibjfr.jar;D:dev toolsjdkjdk8jrelibjfxswt.jar;D:dev toolsjdkjdk8jrelibjsse.jar;D:dev toolsjdkjdk8jrelibmanagement-agent.jar;D:dev toolsjdkjdk8jrelibplugin.jar;D:dev toolsjdkjdk8jrelib
    esources.jar;D:dev toolsjdkjdk8jrelib
    t.jar;E:worksb	argetclasses;E:worklocalRepositoryorgspringframeworkootspring-boot-starter-web1.5.8.RELEASEspring-boot-starter-web-1.5.8.RELEASE.jar;E:worklocalRepositoryorgspringframeworkootspring-boot-starter1.5.8.RELEASEspring-boot-starter-1.5.8.RELEASE.jar;E:worklocalRepositoryorgspringframeworkootspring-boot1.5.8.RELEASEspring-boot-1.5.8.RELEASE.jar;E:worklocalRepositoryorgspringframeworkootspring-boot-starter-logging1.5.8.RELEASEspring-boot-starter-logging-1.5.8.RELEASE.jar;E:worklocalRepositoryorgslf4jjul-to-slf4j1.7.25jul-to-slf4j-1.7.25.jar;E:worklocalRepositoryorgslf4jlog4j-over-slf4j1.7.25log4j-over-slf4j-1.7.25.jar;E:worklocalRepositoryorgyamlsnakeyaml1.17snakeyaml-1.17.jar;E:worklocalRepositoryorgspringframeworkootspring-boot-starter-tomcat1.5.8.RELEASEspring-boot-starter-tomcat-1.5.8.RELEASE.jar;E:worklocalRepositoryorgapache	omcatembed	omcat-embed-core8.5.23	omcat-embed-core-8.5.23.jar;E:worklocalRepositoryorgapache	omcat	omcat-annotations-api8.5.23	omcat-annotations-api-8.5.23.jar;E:worklocalRepositoryorgapache	omcatembed	omcat-embed-el8.5.23	omcat-embed-el-8.5.23.jar;E:worklocalRepositoryorgapache	omcatembed	omcat-embed-websocket8.5.23	omcat-embed-websocket-8.5.23.jar;E:worklocalRepositoryorghibernatehibernate-validator5.3.5.Finalhibernate-validator-5.3.5.Final.jar;E:worklocalRepositoryjavaxvalidationvalidation-api1.1.0.Finalvalidation-api-1.1.0.Final.jar;E:worklocalRepositoryorgjbossloggingjboss-logging3.3.1.Finaljboss-logging-3.3.1.Final.jar;E:worklocalRepositorycomfasterxmlclassmate1.3.4classmate-1.3.4.jar;E:worklocalRepositorycomfasterxmljacksoncorejackson-databind2.8.10jackson-databind-2.8.10.jar;E:worklocalRepositorycomfasterxmljacksoncorejackson-annotations2.8.0jackson-annotations-2.8.0.jar;E:worklocalRepositorycomfasterxmljacksoncorejackson-core2.8.10jackson-core-2.8.10.jar;E:worklocalRepositoryorgspringframeworkspring-web4.3.12.RELEASEspring-web-4.3.12.RELEASE.jar;E:worklocalRepositoryorgspringframeworkspring-aop4.3.12.RELEASEspring-aop-4.3.12.RELEASE.jar;E:worklocalRepositoryorgspringframeworkspring-beans4.3.12.RELEASEspring-beans-4.3.12.RELEASE.jar;E:worklocalRepositoryorgspringframeworkspring-webmvc4.3.12.RELEASEspring-webmvc-4.3.12.RELEASE.jar;E:worklocalRepositoryorgspringframeworkspring-expression4.3.12.RELEASEspring-expression-4.3.12.RELEASE.jar;E:worklocalRepositorycomgithub	obatofastdfs-client1.25.2-RELEASEfastdfs-client-1.25.2-RELEASE.jar;E:worklocalRepositoryorgslf4jslf4j-api1.7.25slf4j-api-1.7.25.jar;E:worklocalRepositoryorgslf4jjcl-over-slf4j1.7.25jcl-over-slf4j-1.7.25.jar;E:worklocalRepositorychqoslogbacklogback-classic1.1.11logback-classic-1.1.11.jar;E:worklocalRepositorychqoslogbacklogback-core1.1.11logback-core-1.1.11.jar;E:worklocalRepositoryorgapachecommonscommons-lang33.3.2commons-lang3-3.3.2.jar;E:worklocalRepositorycommons-beanutilscommons-beanutils1.9.3commons-beanutils-1.9.3.jar;E:worklocalRepositorycommons-collectionscommons-collections3.2.2commons-collections-3.2.2.jar;E:worklocalRepositorycommons-iocommons-io2.4commons-io-2.4.jar;E:worklocalRepositoryorgapachecommonscommons-pool22.4.2commons-pool2-2.4.2.jar;E:worklocalRepositoryorgspringframeworkspring-core4.3.12.RELEASEspring-core-4.3.12.RELEASE.jar;E:worklocalRepositoryorgspringframeworkootspring-boot-autoconfigure1.5.8.RELEASEspring-boot-autoconfigure-1.5.8.RELEASE.jar;E:worklocalRepositoryorgmockitomockito-all1.9.5mockito-all-1.9.5.jar;E:worklocalRepositoryorgspringframeworkspring-context4.3.12.RELEASEspring-context-4.3.12.RELEASE.jar;E:worklocalRepository
    etcoobird	humbnailator.4.8	humbnailator-0.4.8.jar;D:dev toolsideideaIU-2017.2.5.winlibidea_rt.jar" com.wang.sb.SbApplication
    Connected to the target VM, address: '127.0.0.1:59538', transport: 'socket'
    
      .   ____          _            __ _ _
     /\ / ___'_ __ _ _(_)_ __  __ _    
    ( ( )\___ | '_ | '_| | '_ / _` |    
     \/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v1.5.8.RELEASE)
    
    2018-06-14 15:03:26.872  INFO 14760 --- [           main] com.wang.sb.SbApplication                : Starting SbApplication on CFJSWLY with PID 14760 (E:worksb	argetclasses started by admin in E:worksb)
    2018-06-14 15:03:26.892  INFO 14760 --- [           main] com.wang.sb.SbApplication                : The following profiles are active: dev
    2018-06-14 15:03:27.040  INFO 14760 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3697186: startup date [Thu Jun 14 15:03:27 CST 2018]; root of context hierarchy
    2018-06-14 15:03:28.755  INFO 14760 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
    2018-06-14 15:03:28.769  INFO 14760 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-06-14 15:03:28.770  INFO 14760 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
    2018-06-14 15:03:28.935  INFO 14760 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-06-14 15:03:28.935  INFO 14760 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1901 ms
    2018-06-14 15:03:29.185  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'filter2' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'filter3' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'filter4' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'filter5' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'filter1' to: [/*]
    2018-06-14 15:03:29.186  INFO 14760 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
    2018-06-14 15:03:29.401  WARN 14760 --- [           main] figurationPropertiesBindingPostProcessor : The @ConfigurationProperties bean class com.github.tobato.fastdfs.conn.TrackerConnectionManager contains validation constraints but had not been annotated with @Validated.
    2018-06-14 15:03:29.401  WARN 14760 --- [           main] figurationPropertiesBindingPostProcessor : The @ConfigurationProperties bean class com.github.tobato.fastdfs.conn.TrackerConnectionManager contains validation constraints but had not been annotated with @Validated.
    2018-06-14 15:03:29.402  WARN 14760 --- [           main] figurationPropertiesBindingPostProcessor : The @ConfigurationProperties bean class com.github.tobato.fastdfs.conn.TrackerConnectionManager contains validation constraints but had not been annotated with @Validated.
    2018-06-14 15:03:29.852  INFO 14760 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3697186: startup date [Thu Jun 14 15:03:27 CST 2018]; root of context hierarchy
    2018-06-14 15:03:29.928  INFO 14760 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/a]}" onto public java.lang.String com.wang.sb.web.HelloController.hello()
    2018-06-14 15:03:29.930  INFO 14760 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/download]}" onto public void com.wang.sb.web.HelloController.downloadFile(java.lang.String,javax.servlet.http.HttpServletResponse) throws java.io.IOException
    2018-06-14 15:03:29.931  INFO 14760 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/upload]}" onto public java.lang.String com.wang.sb.web.HelloController.uploadFile(org.springframework.web.multipart.MultipartFile) throws java.io.IOException
    2018-06-14 15:03:29.933  INFO 14760 --- [           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-06-14 15:03:29.934  INFO 14760 --- [           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-06-14 15:03:29.970  INFO 14760 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-06-14 15:03:29.970  INFO 14760 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-06-14 15:03:30.030  INFO 14760 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-06-14 15:03:30.287  INFO 14760 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2018-06-14 15:03:30.288  INFO 14760 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'fdfsConnectionPool' has been autodetected for JMX exposure
    2018-06-14 15:03:30.294  INFO 14760 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'fdfsConnectionPool': registering with JMX server as MBean [com.github.tobato.fastdfs.conn:name=fdfsConnectionPool,type=FdfsConnectionPool]
    2018-06-14 15:03:30.360  INFO 14760 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    2018-06-14 15:03:30.368  INFO 14760 --- [           main] com.wang.sb.SbApplication                : Started SbApplication in 4.506 seconds (JVM running for 7.32)

    请求URL(测试filter效果)

    {{env}}/hello/a

    控制台日志

    I'm BFilter
    I'm CFilter
    I'm DFilter
    I'm EFilter
    I'm AFilter

    亲测有效!

  • 相关阅读:
    MVC应用程序使用Entity Framework
    @Styles的nameSpace是什么
    创建第一个MVC应用程序
    计算DataTable某列的值(SUM)
    DropDownList 控件的SelectedIndexChanged事件触发不了
    在类中使用Response.Redirect()方法
    控制某个panel的display样式
    获取指定日期下个月份的第一天
    字符串如何还原为中文
    判断字符串中包含3个连续(升、降)或相同的数字
  • 原文地址:https://www.cnblogs.com/douJiangYouTiao888/p/9183095.html
Copyright © 2011-2022 走看看