programing

Spring Webflux, 정적 콘텐츠를 제공하기 위해 index.html로 전송하는 방법

fastcode 2023. 4. 5. 22:19
반응형

Spring Webflux, 정적 콘텐츠를 제공하기 위해 index.html로 전송하는 방법

spring-boot-starter-webflux(스프링 부트 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);
  }
}
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));
}

스프링 부츠 추적기에 딱지가 있어요

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
        }
    }
}

언급URL : https://stackoverflow.com/questions/45147280/spring-webflux-how-to-forward-to-index-html-to-serve-static-content

반응형