[英]Spring Webflux, How to forward to index.html to serve static content
spring-boot-starter-webflux
(Spring Boot v2.0.0.M2) is already configured like in a spring-boot-starter-web
to serve static content in the static folder in resources. spring-boot-starter-webflux
(Spring Boot v2.0.0.M2)已经像在spring-boot-starter-web
中一样配置为在资源的静态文件夹中提供静态内容。 But it doesn't forward to index.html.但它不会转发到 index.html。 In Spring MVC it is possible to configure like this:在 Spring MVC 中,可以这样配置:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
How to do it in Spring Webflux?在 Spring Webflux 中如何实现?
Do it in WebFilter:在 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);
}
}
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));
}
The same by using WebFlux Kotlin DSL :使用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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.