如何基于 URL 模式应用 Spring Boot 过滤器?

How to apply spring boot filter based on URL pattern?(如何基于 URL 模式应用 Spring Boot 过滤器?)
本文介绍了如何基于 URL 模式应用 Spring Boot 过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我创建了一个 Spring Boot 过滤器 - 使用 @Component 注释实现 GenericFilterBean.

I have created a spring boot filter - implements GenericFilterBean with @Component annotation.

@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 路径,例如 /api/secure/* 但我找不到正确的方法.我试过 @WebFilter 但没有用.我没有使用 XML 配置或 servlet 初始化程序 - 只是注释.

The filter is automatically identified by the Spring Boot Framework and works fine for all of the REST API. I want this filter to apply only on a certain URL path, such as /api/secure/* but I can't find the right way. I tried @WebFilter but it didn't work. I'm not using XML configuration or servlet initializer - just the annotations.

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

What would be the correct way to get it working?

推荐答案

你可以像这样添加过滤器:

You can add a filter like this:

@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();
}

这篇关于如何基于 URL 模式应用 Spring Boot 过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)