spring—有没有一种方法可以在JavaWebFlux中为静态文件提供服务器?

lnxxn5zx  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(276)

大家好,我现在搜索了一整天,我没有找到一个解决方案。我可以在mvcspring应用程序中处理静态文件,没有问题,但是使用webflux我没有找到一种方法来处理它们。
我在ressource中放了一个名为static的文件夹,其中有一个简单的html文件。
我的配置如下:

@Configuration
@EnableWebFlux
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class WebConfig implements WebFluxConfigurer {

    @Bean
    public RouterFunction<ServerResponse> route() {
        return RouterFunctions.resources("/", new ClassPathResource("static/"));
}

当我启动应用程序并转到localhost时,我刚刚收到一个404响应。
我还尝试添加:

spring.webflux.static-path-pattern = /**
spring.web.resources.static-locations = classpath:/static/

到application.properties但是我还是收到了404找不到的。
即使我将thymeleaf添加到依赖项中,我仍然得到404。
希望有人知道该怎么办。

vdzxcuhz

vdzxcuhz1#

我认为您缺少的基本上是告诉您希望为数据服务的请求类型(get)。
这是我在为一个react应用程序提供服务时发现的一段代码 public 文件夹中的 resource 文件夹。
当做一个 GET 反对 /* 我们去拿 index.html . 如果索引包含返回请求的javascript,则它们会被第二个路由器捕获,为服务器中的任何内容提供服务 public 文件夹。

@Configuration
public class HtmlRoutes {

    @Bean
    public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/public/index.html") Resource html) {
        return route(GET("/*"), request -> ok()
                .contentType(MediaType.TEXT_HTML)
                .bodyValue(html)
        );
    }

    @Bean
    public RouterFunction<ServerResponse> imgRouter() {
        return RouterFunctions
                .resources("/**", new ClassPathResource("public/"));
    }
}

相关问题