Java基础、中级、高级、架构面试资料

详解 WebFlux 重定向 redirect

JAVA herman 8408浏览
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

使用 WebFlux 也有一段时间了,最近有一个需求需要用到重定向功能。开发人员无论怎么试都无法让网页进行重定向,然后我谷歌了非常的多的文章。有些文章说不支持类似 spring-mvc 的 forward 功能。有的说要升级到 5.0.2.RELEASE.patch 版本。

最后没办法,我只有去看 ServerResponse 接口的 API 了。发现它里面有 temporaryRedirect 和 permanentRedirect 两个方法可以实现重定向。根据它们的以上就可以知道,一个是临时重定向,一个是永久重定向。temporaryRedirect 代表 302,permanentRedirect 代表 301。

301 重定向与 302 重定向的区别:302 重定向是暂时的重定向,搜索引擎会抓取新的内容而保留旧的网址。301 重定向是永久的重定向,搜索引擎在抓取新内容的同时也将旧的网址替换为重定向之后的网址。

下面我们可以一个 WebFlux 重定向的简单案例。首先 pom.xml 文件还是非常的简单,只需要引入 spring-boot-starter-webflux 即可。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

然后我们创建一个 OAuthWeixinRouter 类,内容如下:

package com.xttblog.router;
import com.xttblog.handler.WeixinHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.*;
/**
 * OAuthWeixinRouter
 * www.xttblog.com
 * @author xtt
 * @date 2019/1/4 下午3:24
 */
@Configuration
public class OAuthWeixinRouter {
    @Autowired
    private WeixinHandler weixinHandler;
    @Bean
    RouterFunction<ServerResponse> routerFunction() {
        return RouterFunctions.route(RequestPredicates.GET("/redirect"), weixinHandler::loginUrl);
    }
}

WeixinHandler 类的代码如下:

package com.xttblog.handler;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.*;
/**
 * WeixinHandler
 * @author xtt
 * @date 2019/1/4 下午3:49
 */
@Component
public class WeixinHandler {
    public Mono<ServerResponse> loginUrl(ServerRequest serverRequest) {
        String TargetUrl = "https://www.xttblog.com";
        return ServerResponse.temporaryRedirect(URI.create(TargetUrl)).build();
    }
}

然后,我们在编写一个 SpringBoot 的启动类,运行项目,在浏览器中输入:http://localhost:8080/redirect,回车后,完美的重定向到 www.xttblog.com 地址。

需要源码的东西,加我微信好友即可。

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » 详解 WebFlux 重定向 redirect