在springboot中如何使用filter设置要排除的URL

 更新时间:2021年12月24日 16:04:50   作者:Airbundey  
这篇文章主要介绍了在springboot中如何使用filter设置要排除的URL,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

使用filter设置要排除的URL

@WebFilter(urlPatterns = "/*")
@Order(value = 1)
public class TestFilter implements Filter {
 
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/main/excludefilter", "/login", "/logout", "/register")));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init-----------filter");
    }
 
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
 
        if (allowedPath) {
            System.out.println("这里是不需要处理的url进入的方法");
            chain.doFilter(req, res);
        }
        else {
            System.out.println("这里是需要处理的url进入的方法");
        }
    }
 
    @Override
    public void destroy() {
        System.out.println("destroy----------filter");
    }
}

@Order中的value越小,优先级越高。

  • ALLOWED_PATHS

这个是一个集合,存放的是需要排出的URL,用来判断是否是需要排除的URL。

关于为什么SpringBoot中使用了@WebFilter但是过滤器却没有生效:一定要加上@Configuration注解,@Service其实也可以,其他类似。

filter指定过滤URL的常见问题

在使用Filter对一些自己指定的URL进行过滤拦截时

经常会出现如下错误

1、 明明在@WebFilter(urlPatterns={"/app/online"})中过滤的是/app/online 路径,但是运行之后发现,这个WebFilter过滤器对所有的URL都进行了过滤。

2、 运行之后发现过滤器没有初始化,没有被加载

下面总结一下使用正确的

合适的注解配置filter的方法:

1、 指定路径

在class 上添加注解@WebFilter(urlPatterns={"/app/online"})

然后在启动类(**Application.java )上添加注解@ServletComponentScan

即可。

代码如下:

2、 过滤所有路径

在class上添加@Component或@Configuration 即可

如果添加了@Component或@Configuration,又添加了@WebFilter(),那么会初始化两次Filter,并且会过滤所有路径+自己指定的路径便会出现对没有指定的URL也会进行过滤

//过滤所有路径
@Component
public class WebFilter implements Filter(){
//override三个方法
。。。
。。。
@Override
 public void init (FilterConfig filterConfig) throws ServletException{
 System.out.println("初始化filter");
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论