Spring Boot使用嵌入式容器,自定義Filter如何配置?

ListenerFilterServlet是Java Web開發過程當中經常使用的三個組件,其中Filter組件的使用頻率最高,常常被用來作簡單的權限處理、請求頭過濾和防止XSS***等。若是咱們使用的是傳統的Spring MVC進行開發,那麼只須要在Tomcat的web.xml文件中進行以下配置便可:css

<!-- 配置Listener -->
<listener>
    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 

<!--配置Filter,這邊配置了一個Filter,可是匹配了多個url-pattern-->
<!-- 以url-partern方式配置的filter中,若是有多個與當前請求匹配,則按web.xml中filter-mapping出現的順序來運行-->
<filter>  
    <filter-name>filter1</filter-name>  
    <filter-class>com.csx.MyFilter</filter-class>  
</filter>  
<filter-mapping>
    <filter-name>filter1</filter-name>  
    <url-pattern>/url/a/*</url-pattern>  
</filter-mapping>  
<filter-mapping>  
    <filter-name>filter1</filter-name>  
    <url-pattern>/url/b/*</url-pattern>  
</filter-mapping>

<!--配置Servlet-->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.spring.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 這邊不建議寫成/* -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

PS:在容器啓動的時候,上面三個組件啓動的順序是Listener --> Filter --> Servlet,這邊安利一個記憶的方法:把啓動順序記憶成「理(Listener)發(Filter)師(Servlet)」便可。web

在web.xml中配置這三個組件比較簡單,可是使用Spring-Boot開發時使用的是嵌入式容器,並無web.xml文件讓咱們進行配置。那麼在Spring-Boot中到底要怎麼配置ListenerFilterServlet等組件呢?spring

本篇博客以Filter爲列,介紹下在Spring-Boot中怎麼配置ListenerFilterServlet等組件。mvc

方式一:將Filter聲明爲bean

這邊咱們先來自定義一個Filter,這個Filter的做用是統計一個接口的調用時間。app

public class TimeConsumingCalculationFilter implements Filter {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest httpRequest=(HttpServletRequest)request;
            long startTime = System.nanoTime();
            logger.info(">>>>>>> Begin ["+httpRequest.getRequestURI()+"]...");
            try{
                chain.doFilter(request, response);
            }finally {
                long endTime = System.nanoTime();
                logger.info(">>>>>>> End ["+httpRequest.getRequestURI()+"]["+(endTime-startTime)/1000/1000.0+"ms].");
            }
        }

    }

在Spring-Boot中配置上面的Filter,咱們只須要在@Configuration文件中作以下配置便可:ide

@Configuration
public class WebConfig {

    private static Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Bean
    public Filter filter1(){
        return new TimeConsumingCalculationFilter();
    }
}

上面的Filter默認會攔截全部請求。假如咱們想要配置多個攔截器的話,只要再加一個Bean方法就能夠了。url

@Configuration
public class WebConfig {

    private static Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Bean
    public Filter filter1(){
        return new TimeConsumingCalculationFilter();
    }

    @Bean
    public Filter filter2() {
        return new TimeConsumingCalculationFilter2();
    }
}

上面的配置代碼配置了兩個Filter,兩個Filter默認都會攔截全部請求,攔截的順序是:filter1-->filter2。這邊的邏輯是先配置的Filter先攔截,後配置的Filter後攔截。固然,若是咱們想明確指定攔截順序的話能夠藉助@Order註解。可是須要注意的是這個註解必定要加在定義的類上面。spa

@Order(Ordered.LOWEST_PRECEDENCE - 2)
public class TimeConsumingCalculationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //your logic
    }

}
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class TimeConsumingCalculationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //your logic
    }

}

PS: @Order中的value值越大,執行的優先級越小。值越小,優先級越大。當咱們自定義執行順序的時候,建議使用@Order(Ordered.LOWEST_PRECEDENCE - 1)這種形式配置,Ordered.LOWEST_PRECEDENCE減去的值越大,優先級越高,這樣看起來比較直觀。代理

另外,Spring還提供了一個OrderedFilter接口,這個接口是FilterOrdered的組合接口,原理和上面的是同樣的。你們能夠看狀況使用。code

上面的這種配置方式優勢是配置起來很是簡單,可是缺點也比較明顯,就是配置不夠靈活,默認會攔截全部請求。

方式二:@WebFilter方式

@WebFilter註解是Servlet中提供的註解,Spring也支持這個註解。@WebFilter能進行細粒度的進行配置,比上面的方式更加靈活。

@Configuration
public class WebConfig {
    //能夠自定義url-pattern
    @WebFilter(urlPatterns="/*")
    @Order(Ordered.LOWEST_PRECEDENCE - 2)
    //這邊若是不加`@Configuration`,須要經過`@ServletComponentScan`掃描`Listener`、`Filter`和`Servlet`這三個組件
    @Configuration
    public class TimeConsumingCalculationFilter implements Filter {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            //your logic
        }
    }   

    @WebFilter(urlPatterns="/*")
    @Order(Ordered.LOWEST_PRECEDENCE - 2)
    //這邊若是不加`@Configuration`,須要經過`@ServletComponentScan`掃描`Listener`、`Filter`和`Servlet`這三個組件
    @Configuration
    public class TimeConsumingCalculationFilter2 implements Filter {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            //your logic
        }
    }   

}

經過 @WebFilter 註解的方式配置Filter簡單,並且可以自定義url-pattern和攔截順序。

方式三:使用FilterRegistrationBean配置

@Configuration
public class WebConfig {

    private static Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Bean
        public FilterRegistrationBean<Filter> filter1() {
            FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
            registrationBean.setName("filter1");
            registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 2);
            registrationBean.setFilter(new TimeConsumingCalculationFilter());
            registrationBean.addUrlPatterns("/foo/*");
            return registrationBean;
        }

        @Bean
        public FilterRegistrationBean<Filter> filter2() {
            FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
            registrationBean.setName("filter2");
            registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 3);
            registrationBean.setFilter(new TimeConsumingCalculationFilter1());
            registrationBean.addUrlPatterns("/*");
            registrationBean.addInitParameter("key1","value1");
            registrationBean.addInitParameter("key2","value2");
            //經過Servlet name匹配Filter,不建議使用
            registrationBean.addServletNames("name1");
            return registrationBean;
        }

}

注意點:

  • FilterRegistrationBean 與 Filter 之間是一對一關係。
  • 若是存在多個 FilterRegistrationBean 須要調用其 setName(String name) 爲其聲明惟一名稱,不然只有第一個註冊成功的有效。
  • 若是須要保證調用順序可經過調用其 setOrder(int order) 方法進行設置。

方式四:使用DelegatingFilterProxyRegistrationBean方式

@Configuration
public class WebConfig {

    @Bean("myFilter")
    //配置了DelegatingFilterProxyRegistrationBean後,這種方式配置的Filter不會生效了,只會攔截/foo/*的請求
    public Filter myFilter(){
        return new TimeConsumingCalculationFilter();
    }

    @Bean
    public DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean(){
        DelegatingFilterProxyRegistrationBean filterProxy = new DelegatingFilterProxyRegistrationBean("myFilter");
        filterProxy.addUrlPatterns("/foo/*");
        filterProxy.addInitParameter("targetFilterLifecycle","true");
        filterProxy.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico");
        filterProxy.setDispatcherTypes(DispatcherType.REQUEST);
        return filterProxy;
    }
}

FilterRegistrationBean和DelegatingFilterProxyRegistrationBean區別:

  • FilterRegistrationBean經過onStartup方法直接註冊filter。
  • DelegatingFilterProxyRegistrationBean是將DelegatingFilterProxy註冊到Servlet3.0+的容器中,同時實現了ApplicationContextAware接口,實例ApplicationContext經過經過傳入自定義filter的名稱查找對應的bean,並生成相應bean的代理對象。

舉一反三

  • 添加自定義Servlet 也可採用方法一@WebServlet 或者ServletRegistrationBean
  • 添加自定義Listener也能夠採用方法一 @WebListener或者ServletListenerRegistrationBean ,注意監聽事件是泛型

其餘相關類

  • ServletComponentRegisteringPostProcessor
  • ServletComponentHandler
  • WebListenerHandler
  • WebFilterHandler
  • WebServletHandler
相關文章
相關標籤/搜索