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<String> 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<java.util.Map<java.lang.String, java.lang.Object>> 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
=======销毁过滤器=========
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,654评论 18 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,399评论 1 92
  • Servlet过滤器是 Servlet 程序的一种特殊用法,主要用来完成一些通用的操作,如编码的过滤、判断用户的登...
    重山杨阅读 1,225评论 0 12
  • 早上醒来一个字累,累的睁不开眼睛,
    遇见继承阅读 133评论 0 0
  • 今天我们看到的这个品类,和诸葛亮一个姓,诸葛菜。它没有磅礴大气的枝头,没有人们都趋之若鹜的外表,它很普通,确是最早...
    vivi_cdd1阅读 735评论 0 0