【问题标题】:Is there a way to server static files in Java Webflux?有没有办法在 Java Webflux 中服务器静态文件?
【发布时间】:2021-07-05 09:35:45
【问题描述】:

大家好,我现在整天都在搜索,但没有找到解决方案。 我可以毫无问题地在 mvc spring 应用程序中提供静态文件,但是使用 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/"));
}

当我启动应用程序并转到本地主机时,我刚刚收到 404 响应。

我也尝试添加:

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

到 application.properties 但我仍然收到 404 not found.

即使我将 Thymeleaf 添加到我的依赖项中,我仍然得到 404。

希望有人知道该怎么做。

【问题讨论】:

    标签: java spring static spring-webflux reactive


    【解决方案1】:

    我认为您缺少的基本上是告诉您要提供数据的请求类型(GET)。

    这是我从resource 文件夹中的public 文件夹中提供反应应用程序时发现的一段旧代码。

    当针对/* 执行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/"));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2012-01-02
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多