Spring Webflux,如何转发index.html来提供静态内容

Igo*_*bak 20 java spring spring-mvc spring-boot spring-webflux

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

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

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

小智 26

在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);
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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));
}
Run Code Online (Sandbox Code Playgroud)