Filter in Springboot

首先用如下代码说明 TestFilter(过滤路径是 /*)和 TestWebFilter ( 过滤路径是 /test) 的实现方法

  • TestFilter 只实现 Filter 接口, 并用 @Component 标注。
  • TestWebFilter 实现 Filter接口, 并用@WebFilter 标注, 且在启动类加 @ServletComponentScan 注解。
  • 此处的Filter 方法会在过滤到对应的请求时打印出请求的 RequestURI

 

 代码:

https://github.com/XLuffyStory/SpringBootStudy/tree/master/filter_demo

 

当 GET localhost:8081/hello 的时候,TestFilter(过滤路径是 /*) 和 TestWebFitler(过滤路径是 /test), 只有 TestFilter 会过滤到 /hello ,所以会有一条log.

 

 

当GET localhost:8081/test 的时候,因为有TestFilter(过滤路径是 /*) 和 TestWebFitler(过滤路径是 /test),所以会有两条log.

 

 

 下面说为什么用Filter:

 

1. filter 的一种用法:可以在filter中根据条件决定是否调用chain.doFilter(request, response)方法, 即是否让目标资源(Controller 方法)执行。

 当在TestWebFilter 中注释掉 chain.doFilter(request, response); GET localhost:8081/test 是没有返回值的,即如下Controller 方法没有得到执行

@GetMapping("/test")
    public String test() {
    return "Hello Test";
    }

 2. 另一种用法是在 doFilter 方法中做一些预处理:

 Reference:

https://www.cnblogs.com/ooo0/p/10360952.html

https://www.cnblogs.com/huanzi-qch/p/11239167.html

posted @ 2020-11-25 21:24  Happy2Share  阅读(76)  评论(0编辑  收藏  举报