spring cloud gateway自定义filter重定向

12 篇文章 1 订阅
9 篇文章 0 订阅

在自定义filter里返回值是一个Mono<Void> 如果业务处理发现数据有问题就要返回

这时就有了第一种实现,retrun 一个 

Mono.empty();

这种处理办法显然是有问题的,用户根本无从知道他的数据问题在哪。你返回Mono<Void>没有任何意义。只是让fliter停止了而已。

这时就要去查看源码里怎么写的了,我发现了

org.springframework.cloud.gateway.filter.factory.RedirectToGatewayFilterFactory这个类里的一个方法。

它向responseheader里set了Location 然后return 了response.setComplete();  而这个方法正好返回一个

我们可以使用这个方法实现页面的重定向。

  /**
     * 失败返回message提示用户
     * @param exchange
     * @param url
     * @return
     */

    private Mono<Void> fallBack(String url,ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", "你的url");
        return exchange.getResponse().setComplete();
    }

调用这个方法就可以实现。

2019-11-29更新 上面的方法只能在httpstatus 3xx下返回,如果使用其他返回值 无法带返回结果


    private Mono<Void> returnMessage(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        HttpStatus httpStatus = HttpStatus.OK;
        String resultStr = "xxxx";
        byte[] bits = resultStr.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(httpStatus == null ? HttpStatus.OK : httpStatus);
        //指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

 在filter中直接return 即可

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值