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中执行此操作?
答案 0 :(得分:21)
在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);
}
}
答案 1 :(得分:7)
答案 2 :(得分:4)
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).syncBody(indexHtml));
}
答案 3 :(得分:0)
使用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
}
}
}