• 如何定义Spring Boot Filter


    1.概述

    在本教程中,我们将探索如何定义自定义过滤器并在Spring Boot的帮助下指定其调用顺序。

    2.定义过滤器和调用顺序

    让我们从创建两个过滤器开始:

    1. TransactionFilter - 启动和提交事务
    2. RequestResponseLoggingFilter - 记录请求和响应

    为了创建过滤器,我们需要简单地实现Filter接口:

    @Component
    @Order(1)
    public class TransactionFilter implements Filter {
     
        @Override
        public void doFilter
          ServletRequest request, 
          ServletResponse response, 
          FilterChain chain) throws IOException, ServletException {
      
            HttpServletRequest req = (HttpServletRequest) request;
            LOG.info(
              "Starting a transaction for req : {}", 
              req.getRequestURI());
      
            chain.doFilter(request, response);
            LOG.info(
              "Committing a transaction for req : {}", 
              req.getRequestURI());
        }
     
        // other methods 
    }
    @Component
    @Order(2)
    public class RequestResponseLoggingFilter implements Filter {
     
        @Override
        public void doFilter(
          ServletRequest request, 
          ServletResponse response, 
          FilterChain chain) throws IOException, ServletException {
      
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            LOG.info(
              "Logging Request  {} : {}", req.getMethod(), 
              req.getRequestURI());
            chain.doFilter(request, response);
            LOG.info(
              "Logging Response :{}", 
              res.getContentType());
        }
     
        // other methods
    }
     
     

    为了使Spring能够识别过滤器,我们需要使用@Component注释将其定义为bean 

    并且,为了让过滤器以正确的顺序触发 - 我们需要使用@Order注释。

    2.1.使用URL模式过滤

    在上面的示例中,我们的过滤器默认为我们的应用程序中的所有URL注册。

    但是,我们有时可能希望过滤器仅适用于某些URL模式。

    在这种情况下,我们必须从过滤器类定义中删除@Component注释,并使用FilterRegistrationBean注册过滤器

    @Bean
    public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter(){
        FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean 
          = new FilterRegistrationBean<>();
             
        registrationBean.setFilter(new RequestResponseLoggingFilter());
        registrationBean.addUrlPatterns("/users/*");
             
        return registrationBean;    
    }
     

    现在,过滤器仅适用于与/ users / *模式匹配的路径

    要设置过滤器的URL模式,我们可以使用addUrlPatterns()setUrlPatterns()方法。

    3.一个快速示例

    现在让我们创建一个简单的端点并向其发送HTTP请求:

    @RestController
    @RequestMapping("/users")
    public class UserController {
         
        @GetMapping()
        public List<User> getAllUsers() {
            // ...
        }
    }
     

    登录此API的应用程序输出是:

    23:54:38 INFO  com.spring.demo.TransactionFilter - Starting Transaction for req :/users
    23:54:38 INFO  c.s.d.RequestResponseLoggingFilter - Logging Request  GET : /users
    ...
    23:54:38 INFO  c.s.d.RequestResponseLoggingFilter - Logging Response :application/json;charset=UTF-8
    23:54:38 INFO  com.spring.demo.TransactionFilter - Committing Transaction for req :/users
     

    这确认了按所定义顺序调用过滤器。

    4.结论

    在本文中,我们总结了如何在Spring Boot webapp中定义自定义过滤器

  • 相关阅读:
    【已解决】github中git push origin master出错:error: failed to push some refs to
    好记心不如烂笔头,ssh登录 The authenticity of host 192.168.0.xxx can't be established. 的问题
    THINKPHP 5.0目录结构
    thinkphp5.0入口文件
    thinkphp5.0 生命周期
    thinkphp5.0 架构
    Django template
    Django queryset
    Django model
    Python unittest
  • 原文地址:https://www.cnblogs.com/gc65/p/10628818.html
Copyright © 2020-2023  润新知