Spring boot 注册过滤器的方式

方式一

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;

import java.io.IOException;

@WebFilter("/*")
public class Filter01 implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

此种方式的问题在于无法指定 Filter 的优先级。

方式二

该方式使用 Compontent 注解声明,并使用Order注解来配置优先级,缺点是无法指定拦截的路径(默认拦截所有)

package com.haoyang.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(100)
public class Filter02 implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

方式三

使用配置的方式可以完美解决前两种方式遇到的问题。

package com.haoyang.config;

import com.haoyang.filter.Filter01;
import com.haoyang.filter.Filter02;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class FilterConfig {
    @Bean
    FilterRegistrationBean<Filter01> filter01FilterRegistrationBean() {
        FilterRegistrationBean<Filter01> bean = new FilterRegistrationBean<Filter01>();
        bean.setFilter(new Filter01());
        bean.setOrder(99);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

    @Bean
    FilterRegistrationBean<Filter02> filter02FilterRegistrationBean() {
        FilterRegistrationBean<Filter02> bean = new FilterRegistrationBean<Filter02>();
        bean.setFilter(new Filter02());
        bean.setOrder(99);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

你可能感兴趣的:(JAVA,spring,boot,java)