Java SpringWebFlux,如何转发到index.html以提供静态内容
Java SpringWebFlux,如何转发到index.html以提供静态内容,java,spring,spring-mvc,spring-boot,spring-webflux,Java,Spring,Spring Mvc,Spring Boot,Spring Webflux,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(
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中执行此操作?在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);
}
}
@组件
公共类CustomWebFilter实现WebFilter{
@凌驾
公共Mono筛选器(服务器WebExchange exchange、WebFilterChain链){
if(exchange.getRequest().getURI().getPath().equals(“/”){
返回chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path(“/index.html”).build()).build());
}
返回链。过滤器(交换);
}
}
有一个。导入静态org.springframework.web.reactive.function.server.RequestPredicates.GET;
导入静态org.springframework.web.reactive.function.server.RouterFunctions.route;
导入静态org.springframework.web.reactive.function.server.ServerResponse.ok;
@豆子
公共路由函数indexRouter(@Value(“classpath:/static/index.html”)最终资源indexHtml){
返回路由(GET(“/”,request->ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml));
}
使用以下方法进行相同操作:
@Bean
open fun indexRouter():RouterFunction{
val redirectToIndex=
服务器响应
.temporaryRedirect(URI(“/index.html”))
.build()
返回路由器{
获取(“/”){
redirectToIndex//您也可以在此处创建请求
}
}
}
这一个比过滤器好谢谢,这是拼图中的最后一块。这没关系,但对于动态需求来说不是这样ok@kakabali取决于动态的含义,但它可以很好地处理事物,例如/blog/{id}/comments
(这是一个动态路由)。我如何通过转发而不是重定向来完成此操作?@lfmunoz,我没有找到转发http状态。可能有预先构建的功能。但是,您可以使用如下构造构造自己的响应:ServerResponse.status(HttpStatus.I\u AM\u A\u TEAPOT).header(“我的header”,“2342”)
,只需将正确的status和正确的header放在那里
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));
}
@Bean
open fun indexRouter(): RouterFunction<ServerResponse> {
val redirectToIndex =
ServerResponse
.temporaryRedirect(URI("/index.html"))
.build()
return router {
GET("/") {
redirectToIndex // also you can create request here
}
}
}