Spring Webflux, How to forward to index.html to se

2020-05-25 04:55发布

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. But it doesn't forward to index.html. In Spring MVC it is possible to configure like this:

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

How to do it in Spring Webflux?

4条回答
淡お忘
2楼-- · 2020-05-25 05:34

Do it in 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);
  }
}
查看更多
我想做一个坏孩纸
3楼-- · 2020-05-25 05:43
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));
}
查看更多
The star\"
5楼-- · 2020-05-25 05:56

The same by using 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
        }
    }
}
查看更多
登录 后发表回答