webflux资源路由器无法正常工作

时间:2019-12-04 20:59:30

标签: spring-boot spring-webflux

我正在尝试使用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 &quot;/path/css/style.css&quot; [ExceptionHandlingWebHandler]

1 个答案:

答案 0 :(得分:1)

在您的HTML代码段中,您应该使用这样的绝对路径:

<link rel="stylesheet" href="/css/style.css">

使用相对路径css/styles.css使您的浏览器认为它应该请求相对于当前页面的资源,因此/path/css/style.css。问题不在您的路由器中,而是在您的模板中。

相关问题