Spring Boot 注入 Filter 过滤器的几种方式

Spring Boot About 2,282 words

FilterRegistrationBean

推荐使用FilterRegistrationBean方式。

@Configuration(proxyBeanMethods = false)
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<TestFilter> filterRegistrationBean() {
        FilterRegistrationBean<TestFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new TestFilter());
        filterRegistrationBean.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        filterRegistrationBean.setUrlPatterns(Collections.singleton("/api/*"));
        return filterRegistrationBean;
    }

}

@ServletComponentScan

启动类上添加@ServletComponentScan,扫描Servlet组件。

@ServletComponentScan
@SpringBootApplication
public class FilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(FilterApplication.class, args);
    }

}

编写Filter,添加@WebFilter,设置过滤路径urlPatterns@Order设置过滤器顺序。

@Slf4j
@WebFilter(urlPatterns = {"/api/*"})
@Order
public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("token filter init#{}", filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("token filter doFilter#{}", request.getServletPath());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("token filter destroy");
    }
}

@Component

使用@Component注解注入的Filter,只能作用于根路径/*@WebFilter不起作用。

@Slf4j
@Component
// @WebFilter(urlPatterns = {"/filter/*"})
public class MyHttpFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try (ServletInputStream inputStream = request.getInputStream()) {
            String req = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("my http filter doFilter#{}, req#{}", request.getServletPath(), req);
        }
        super.doFilter(request, response, chain);
    }
}
Views: 1,598 · Posted: 2023-01-21

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh