SpringBoot拾级而上·自定义过滤器

一、编写过滤器

package com.springboot.springboot_web.Filter;

import javax.servlet.*;
import java.io.IOException;

public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("=======初始化过滤器=========");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        long start = System.currentTimeMillis();
        filterChain.doFilter(request, response);
        System.out.println("filter 耗时:" + (System.currentTimeMillis() - start));
    }

    @Override
    public void destroy() {
        System.out.println("=======销毁过滤器=========");
    }

}

二、要是该过滤器生效,有两种方式:

  1. 使用 @Component 注解
  2. 添加到过滤器链中,此方式适用于使用第三方的过滤器。将过滤器写到 WebConfig 类中,如下
    @Bean
    public FilterRegistrationBean timeFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        TimeFilter timeFilter = new TimeFilter();
        registrationBean.setFilter(timeFilter);
        List urls = new ArrayList<>();
        urls.add("/*");
        registrationBean.setUrlPatterns(urls);
        return registrationBean;
    }

启动服务,发现打印了如下的日志

2018-08-01 11:32:13.451 |-INFO  [localhost-startStop-1] org.springframework.web.context.ContextLoader [285] -| Root WebApplicationContext: initialization completed in 219 ms
2018-08-01 11:32:13.477 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.ServletRegistrationBean [186] -| Servlet servletTest mapped to [/servletTest]
2018-08-01 11:32:13.478 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.ServletRegistrationBean [186] -| Servlet dispatcherServlet mapped to [/]
2018-08-01 11:32:13.480 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.FilterRegistrationBean [245] -| Mapping filter: 'characterEncodingFilter' to: [/*]
2018-08-01 11:32:13.481 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.FilterRegistrationBean [245] -| Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-08-01 11:32:13.481 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.FilterRegistrationBean [245] -| Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-08-01 11:32:13.481 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.FilterRegistrationBean [245] -| Mapping filter: 'requestContextFilter' to: [/*]
2018-08-01 11:32:13.482 |-INFO  [localhost-startStop-1] org.springframework.boot.web.servlet.FilterRegistrationBean [258] -| Mapping filter: 'timeFilter' to urls: [/*]
=======初始化过滤器=========
2018-08-01 11:32:13.523 |-INFO  [restartedMain] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping [373] -| Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-01 11:32:13.547 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter [574] -| Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6a84b0a8: startup date [Wed Aug 01 11:32:13 CST 2018]; root of context hierarchy
2018-08-01 11:32:13.553 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/fastjson/test]}" onto public com.springboot.springboot_web.model.User com.springboot.springboot_web.control.FastjsonController.testJson()
2018-08-01 11:32:13.558 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/springboot/getUserByGet],methods=[GET]}" onto java.lang.String com.springboot.springboot_web.control.HttpDemoControl.getUserByGet(java.lang.String)
2018-08-01 11:32:13.558 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/springboot/getUserByPost],methods=[POST]}" onto java.lang.String com.springboot.springboot_web.control.HttpDemoControl.getUserByPost(java.lang.String)
2018-08-01 11:32:13.559 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/springboot/getUserByJson],methods=[POST]}" onto java.lang.String com.springboot.springboot_web.control.HttpDemoControl.getUserByJson(java.lang.String)
2018-08-01 11:32:13.560 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-08-01 11:32:13.560 |-INFO  [restartedMain] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping [547] -| Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-08-01 11:32:13.565 |-INFO  [restartedMain] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping [373] -| Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-01 11:32:13.565 |-INFO  [restartedMain] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping [373] -| Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-01 11:32:13.594 |-INFO  [restartedMain] org.springframework.boot.devtools.autoconfigure.OptionalLiveReloadServer [57] -| LiveReload server is running on port 35729
2018-08-01 11:32:13.606 |-INFO  [restartedMain] org.springframework.jmx.export.annotation.AnnotationMBeanExporter [433] -| Registering beans for JMX exposure on startup
2018-08-01 11:32:13.610 |-INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol [180] -| Starting ProtocolHandler ["http-nio-8081"]
2018-08-01 11:32:13.611 |-INFO  [restartedMain] org.apache.tomcat.util.net.NioSelectorPool [180] -| Using a shared selector for servlet write/read
2018-08-01 11:32:13.613 |-INFO  [restartedMain] org.springframework.boot.web.embedded.tomcat.TomcatWebServer [206] -| Tomcat started on port(s): 8081 (http) with context path ''
2018-08-01 11:32:13.613 |-INFO  [restartedMain] com.springboot.springboot_web.SpringbootWebApplication [59] -| Started SpringbootWebApplication in 0.414 seconds (JVM running for 152.783)
2018-08-01 11:32:13.614 |-INFO  [restartedMain] org.springframework.boot.devtools.autoconfigure.ConditionEvaluationDeltaLoggingListener [56] -| Condition evaluation unchanged

访问 http://127.0.0.1:8081/servletTest ,打印日志如下,

filter 耗时:1
2018-08-01 11:36:33.719 |-INFO  [http-nio-8081-exec-2] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] [180] -| Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-01 11:36:33.719 |-INFO  [http-nio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet [494] -| FrameworkServlet 'dispatcherServlet': initialization started
2018-08-01 11:36:33.742 |-INFO  [http-nio-8081-exec-2] org.springframework.web.servlet.DispatcherServlet [509] -| FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
filter 耗时:32

关闭服务,打印日志如下

2018-08-01 11:37:00.183 |-INFO  [Thread-34] org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext [993] -| Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6a84b0a8: startup date [Wed Aug 01 11:32:13 CST 2018]; root of context hierarchy
2018-08-01 11:37:00.185 |-INFO  [Thread-34] org.springframework.jmx.export.annotation.AnnotationMBeanExporter [451] -| Unregistering JMX-exposed beans on shutdown
=======销毁过滤器=========

你可能感兴趣的:(SpringBoot拾级而上·自定义过滤器)