我正在尝试使用webflux进行一些非常简单的操作-提供静态页面
文件夹结构
-- resources
-- public
myPage.html
-- css
style.css
路由器
@Bean
public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/public/myPage.html") Resource html) {
return route(GET("/path/myPage"),
request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(html));
}
@Bean
public RouterFunction<ServerResponse> imgRouter() {
return RouterFunctions.resources("/**", new ClassPathResource("/public/"));
}
HTML代码段
<header>
<link rel="stylesheet" href="css/style.css">
...
</header>
调用http://example.com/path/myPage
确实为该页面提供了服务,但是css部分却得到了404
在logging.level.org.springframework.web: TRACE
上运行,我发现styles.css
被解析为/path/css/style.css
,而没有在/public/css/style.css
下搜索,这是我的问题。
Error has been observed at the following site(s):
|_ checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
|_ checkpoint ⇢ HTTP GET "/path/css/style.css" [ExceptionHandlingWebHandler]
答案 0 :(得分:1)
在您的HTML代码段中,您应该使用这样的绝对路径:
<link rel="stylesheet" href="/css/style.css">
使用相对路径css/styles.css
使您的浏览器认为它应该请求相对于当前页面的资源,因此/path/css/style.css
。问题不在您的路由器中,而是在您的模板中。