首页 > 解决方案 > 有没有办法在spring webflux中为特定的url执行WebFilter

问题描述

我有一个 WebFilter,我想排除几个 url。

我使用了 PathPattern,它可以用来排除 1 个 url,但不能超过。

私有最终路径模式路径模式;

public MyFilter() {
    pathPattern = new PathPatternParser().parse("/url");
}

                            

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

    if (pathPattern.matches(exchange.getRequest().getPath().pathWithinApplication())) {
        return chain.filter(exchange);
    }

标签: spring-webflux

解决方案



有多种方法可以做到,下面是其中一种方法

@Slf4j
@Component
public class LogFilter implements WebFilter {

    List<PathPattern> pathPatternList;

    public LogFilter() {
        PathPattern pathPattern1 = new PathPatternParser()
                .parse("/admin");
        PathPattern pathPattern2 = new PathPatternParser().parse("/emp");
        pathPatternList = new ArrayList<>();
        pathPatternList.add(pathPattern1);
        pathPatternList.add(pathPattern2);

    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        RequestPath path = exchange.getRequest().getPath();
        if (pathPatternList.stream().anyMatch(pathPattern -> pathPattern.matches(path.pathWithinApplication()))) {
            log.info(path.toString() + " path excluded");
            return chain.filter(exchange);
        }
        log.info("executing logic for " + path.toString() + " path");
        return chain.filter(exchange);

    }
}

对于 Url /admin/emp它将排除其他 url 的逻辑,它将执行日志下面的逻辑检查

2019-05-10 00:20:55.660  INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter         : /admin path excluded
2019-05-10 00:20:55.661  INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.AdminController         : get admin
2019-05-10 00:20:58.361  INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter         : /emp path excluded
2019-05-10 00:20:58.362  INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.EmployeeController      : get employee
2019-05-10 00:21:03.649  INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter         : executing logic for /messages/10 path
2019-05-10 00:21:03.651  INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.StoresController        : getting message details for id 10 enter code here

我希望这能回答你的问题
谢谢


推荐阅读