如何根据URL模式应用弹簧引导过滤器?

2022-09-01 13:34:51

我创建了一个弹簧引导过滤器 - 带有注释的实现。GenericFilterBean@Component

@Component 
public class MyAuthenticationFilter  extends GenericFilterBean {
...
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
...
}
}

该过滤器由Spring Boot Framework自动识别,并且适用于所有REST API。我希望此过滤器仅应用于某个URL路径,例如,但我找不到正确的方法。我试过了,但它不起作用。我没有使用XML配置或servlet初始值设定项 - 只是注释。/api/secure/*@WebFilter

让它工作的正确方法是什么?


答案 1

如果能够扩展,则还有另一个选项。例如:OncePerRequestFilter

public class SomeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // your filter logic ....
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getServletPath();
        return !path.startsWith("/api/secure/");
    }
}

答案 2

您可以添加如下过滤器:

@Bean
public FilterRegistrationBean someFilterRegistration() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(someFilter());
    registration.addUrlPatterns("/url/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("someFilter");
    registration.setOrder(1);
    return registration;
} 

@Bean(name = "someFilter")
public Filter someFilter() {
    return new SomeFilter();
}

推荐