在Spring Boot中注册过滤器几种方式

发布时间:2024年01月18日

1. 使用@WebFilter注解(适用于Servlet API项目)

import jakarta.servlet.annotation.WebFilter;

@WebFilter(urlPatterns = "/*") // 拦截所有请求
public class TokenFilter implements Filter {
    // 实现doFilter方法,添加过滤逻辑
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // ... 过滤器逻辑
        chain.doFilter(request, response);
    }

    // 其他生命周期方法如init和destroy...
}

2. 使用Spring的FilterRegistrationBean(推荐)

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<TokenFilter> tokenFilterRegistration() {
        FilterRegistrationBean<TokenFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new TokenFilter());
        // 设置拦截规则
        registration.addUrlPatterns("/*"); // 拦截所有请求
        // 可以设置过滤器名称、初始化参数等
        registration.setName("tokenFilter");
        // 设置过滤器执行顺序,默认为0,数值越小优先级越高
        registration.setOrder(1);
        return registration;
    }
}

// TokenFilter类实现javax.servlet.Filter接口
public class TokenFilter implements Filter {
    // ...
}

3. 如果过滤器是Spring Bean,可以通过继承GenericFilterBean

import org.springframework.web.filter.GenericFilterBean;

public class TokenFilter extends GenericFilterBean {
    // 实现doFilterInternal方法替代doFilter方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // ... 过滤器逻辑
        chain.doFilter(request, response);
    }
}

// 注册到Spring容器中
@Configuration
public class FilterConfig {

    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

    // 若需指定URL模式或排序,同样可以使用FilterRegistrationBean
    @Bean
    public FilterRegistrationBean<TokenFilter> tokenFilterRegistration(TokenFilter tokenFilter) {
        FilterRegistrationBean<TokenFilter> registration = new FilterRegistrationBean<>(tokenFilter);
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }
}

文章来源:https://blog.csdn.net/weixin_37646636/article/details/135645129
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。