• 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

  • 相关阅读:
    浅谈树的重心
    倍增的奇妙用处
    KMP——从入门到不会打题
    万能的进制哈希
    浅谈扫描线算法的应用
    无需Flash录视频——HTML5中级进阶
    一个模仿微信群聊的H5页面
    关于建议
    前端技术学习线路
    Kurento安装与入门02——运行示例前的准备
  • 原文地址:https://www.cnblogs.com/luffystory/p/14038847.html
Copyright © 2020-2023  润新知