Spring Boot:自定义filter

作者: 聪明的奇瑞 | 来源:发表于2017-12-28 17:50 被阅读572次

    前言

    • 传统的 JavaEE 添加 Filter 是在 web.xml 中配置或注解方式,然而 spring-boot 中显然不能这样实现
    <filter>
         <filter-name>TestFilter</filter-name>
            <filter-class>com.cppba.filter.TestFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>TestFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <init-param>
           <param-name>paramName</param-name>
           <param-value>paramValue</param-value>
        </init-param>
    </filter-mapping>
    

    方法一

    创建自定义 Filter

    public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("TestFilter");
    }
    
    @Override
    public void destroy() {
    
    }
    }
    

    通过 @Bean 将过滤器注入到 IOC 容器中,并通过 setOrder 方法设置过滤器位置(过滤器链中的位置)

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TestFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("testFilter");
        registration.setOrder(1);
        return registration;
    }
    

    方法二

    创建自定义 Filter 并添加 Servlet3 的 @WebFilter 注解,@Order 为过滤器链中的位置

    @Order(1)
    //重点
    @WebFilter(filterName = "testFilter1", urlPatterns = "/*")
    public class TestFilterFirst implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
                throws IOException, ServletException {
            System.out.println("TestFilter1");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    

    在启动类上添加扫描

    @SpringBootApplication(scanBasePackages = "com.cppba")
    //重点
    @ServletComponentScan
    public class Application {
        public static void main(String[] args) throws UnknownHostException {
            SpringApplication app = new SpringApplication(Application.class);
            Environment environment = app.run(args).getEnvironment();
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring Boot:自定义filter

        本文链接:https://www.haomeiwen.com/subject/akbvgxtx.html