24

spring-boot-starter-webflux(Spring Boot v2.0.0.M2) 已经配置spring-boot-starter-web为在资源中的静态文件夹中提供静态内容。但它不会转发到 index.html。在 Spring MVC 中,可以这样配置:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

如何在 Spring Webflux 中做到这一点?

4

4 回答 4

35

在 WebFilter 中执行此操作:

@Component
public class CustomWebFilter implements WebFilter {
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (exchange.getRequest().getURI().getPath().equals("/")) {
        return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path("/index.html").build()).build());
    }

    return chain.filter(exchange);
  }
}
于 2017-07-19T12:32:10.553 回答
11
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

@Bean
public RouterFunction<ServerResponse> indexRouter(@Value("classpath:/static/index.html") final Resource indexHtml) {
return route(GET("/"), request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml));
}
于 2018-05-14T06:50:04.230 回答
9

Spring Boot 跟踪器中有一张

于 2017-07-19T14:04:08.207 回答
3

使用WebFlux Kotlin DSL 也是如此

@Bean
open fun indexRouter(): RouterFunction<ServerResponse> {
    val redirectToIndex =
            ServerResponse
                    .temporaryRedirect(URI("/index.html"))
                    .build()

    return router {
        GET("/") {
            redirectToIndex // also you can create request here
        }
    }
}
于 2019-04-03T13:26:32.423 回答