栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

webflux webfilter跳过后续filter及重定向的实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

webflux webfilter跳过后续filter及重定向的实现

跳过后续filter实现

碰到个需求,webflux中如果想跳过后续的webfilter,如果直接返回的话,可以直接return

Mono.empty(),但是这样就无法执行最终的controller。

默认的 chain.filter 源码(DefaultWebFilterChain中)如下:

	public Mono filter(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 filter(ServerWebExchange exchange, WebFilterChain chain) {
    // 其他业务代码
    return Mono.defer(() -> ((DefaultWebFilterChain) chain).getHandler().handle(exchange));
}
类似springmvc中redirect重定向实现

springmvc中,如果想从filter直接重定向到其他的controller mapping方法,可以通过redirect实现,webflux中没有这个方法,查看源码可知,执行过程为:

HttpWebHandlerAdapter#handle-->ExceptionHandlingWebHandler#handle-->FilteringWebHandler#handle-->DispatcherHandler#handle

DispatcherHandler#handle方法如下:

    public Mono handle(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 Mono filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(exchange.mutate()
                .request(builder -> builder.path("需要重定向的url")).build());
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/962280.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号