【问题标题】:Spring Webflux, How to forward to index.html to serve static contentSpring Webflux,如何转发到 index.html 以提供静态内容
【发布时间】:2017-12-22 04:05:36
【问题描述】:

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中怎么做?

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-webflux


    【解决方案1】:

    在 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);
      }
    }
    

    【讨论】:

    • 这没关系,但对于动态需求,它不是那么好
    • @kakabali 取决于您的意思是动态的,但它适用于例如 /blog/{id}/comments 的东西(这是一条动态路线)。
    【解决方案2】:

    【讨论】:

      【解决方案3】:
      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));
      }
      

      【讨论】:

      • 这个比过滤器好
      • 谢谢,这是拼图中的最后一块。
      【解决方案4】:

      同样使用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
              }
          }
      }
      

      【讨论】:

      • 如何通过转发而不是重定向来做到这一点?
      • @lfmunoz,我没有找到转发 http 状态。可能,有预建的功能。但是,您可以像这样构造自己的响应:ServerResponse .status(HttpStatus.I_AM_A_TEAPOT) .header("my-header", "2342"),只需将正确的状态和正确的标题放在那里
      猜你喜欢
      • 2017-09-23
      • 2012-08-02
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2011-10-14
      • 2017-02-21
      相关资源
      最近更新 更多