有没有办法在 Java Webflux 中服务器静态文件?
Is there a way to server static files in Java Webflux?
大家好,我现在正在搜索一整天,但没有找到解决方案。
我可以在 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 未找到。
即使我将 Thymeleaf 添加到我的依赖项中,我仍然得到 404。
希望有人知道该怎么做。
我认为你缺少的基本上是告诉你想要提供数据的请求类型 (GET)。
这是我在 resource
文件夹中的 public
文件夹中为 React 应用程序提供服务时发现的一段旧代码。
当对 /*
执行 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/"));
}
}
大家好,我现在正在搜索一整天,但没有找到解决方案。 我可以在 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 未找到。
即使我将 Thymeleaf 添加到我的依赖项中,我仍然得到 404。
希望有人知道该怎么做。
我认为你缺少的基本上是告诉你想要提供数据的请求类型 (GET)。
这是我在 resource
文件夹中的 public
文件夹中为 React 应用程序提供服务时发现的一段旧代码。
当对 /*
执行 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/"));
}
}