碰到个需求,webflux中如果想跳过后续的webfilter,如果直接返回的话,可以直接return
Mono.empty(),但是这样就无法执行最终的controller。
默认的 chain.filter 源码(DefaultWebFilterChain中)如下:
public Monofilter(ServerWebExchange exchange) { return Mono.defer(() -> this.currentFilter != null && this.chain != null ? invokeFilter(this.currentFilter, this.chain, exchange) : this.handler.handle(exchange)); }
从源码可知,当存在后续filter时,会继续往下调用,否则直接调用handler.handle方法,因此只要拿到对应的handler直接调用,跳过 invokeFilter 判断即可
可以直接在webfilter中直接调用handler,即:
public Mono类似springmvc中redirect重定向实现filter(ServerWebExchange exchange, WebFilterChain chain) { // 其他业务代码 return Mono.defer(() -> ((DefaultWebFilterChain) chain).getHandler().handle(exchange)); }
springmvc中,如果想从filter直接重定向到其他的controller mapping方法,可以通过redirect实现,webflux中没有这个方法,查看源码可知,执行过程为:
HttpWebHandlerAdapter#handle-->ExceptionHandlingWebHandler#handle-->FilteringWebHandler#handle-->DispatcherHandler#handle
DispatcherHandler#handle方法如下:
public Monohandle(ServerWebExchange exchange) { if (this.handlerMappings == null) { return createNotFoundError(); } return Flux.fromIterable(this.handlerMappings) .concatMap(mapping -> mapping.getHandler(exchange)) .next() .switchIfEmpty(createNotFoundError()) .flatMap(handler -> invokeHandler(exchange, handler)) .flatMap(result -> handleResult(exchange, result)); }
因此,filter执行,在DispatcherHandler的handlerMappings匹配之前,只需要在filter中修改url即可实现该需求,代码如下:
public Monofilter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange.mutate() .request(builder -> builder.path("需要重定向的url")).build()); }



