上一篇博文介紹SpringMVC的靜態資源訪問,那么在WebFlux中,靜態資源的訪問姿勢是否一致呢
I. 默認配置
與SpringBoot的默認配置一樣,WebFlux同樣是classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
即,將靜態文件放在這四個目錄下,可以直接訪問
1. 項目演示
創建一個SpringBoot項目,添加依賴(本文使用的版本為: 2.2.1-RELEASE
)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
在資源路徑下添加目錄 static
,目錄下添加兩個html文件,如下圖
實現啟動類,不添加額外邏輯,既可以直接通過完整url方式訪問靜態資源
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
主要觀察上面三個請求,放在index.html
是無法直接訪問到的,因為它所在的目錄並不在默認的四個靜態資源路徑中
2. Url映射
上面是直接通過靜態資源文件名的方式進行訪問,那么WebFlux是否可以實現SpringMVC那種,根據視圖名返回View的方式呢?
@Controller
public class ViewAction {
@GetMapping(path = "a")
public String a() {
return "a.html";
}
}
直接訪問,結果發現500,找不到名為a.html
的視圖
這種方式不行的話,改用WebFlux的路由寫法
@Bean
public RouterFunction<ServerResponse> indexRouter() {
return RouterFunctions.route(RequestPredicates.GET("/b"),
request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue("b.html");
}
II. 自定義配置路徑
如果我們希望指定一個自定義的路徑,是否可以如SpringMvc那樣,修改配置or代碼設置映射完成呢?
在資源目錄下,新加兩個文件夾,分別是 o1, o2
1. 配置修改
如SpringMVC,修改靜態資源配置
spring:
resources:
static-locations: classpath:/o1/,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
然后訪問 /o1.html
,發現404,這種直接修改配置方式不行!!!
2. WebFluxConfigurer添加映射
直接修改啟動類,實現WebFluxConfigurer
接口,手動添加資源映射
@SpringBootApplication
public class Application implements WebFluxConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/o2/");
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
接着訪問 /o2.html
3. @Value方式
除了上述手動映射的方式之外,還有一種非主流的是方式,如
@Bean
public RouterFunction<ServerResponse> indexRouter(@Value("classpath:/index.html") final Resource indexHtml,
@Value("classpath:/self/s.html") final Resource sHtml) {
return RouterFunctions.route(RequestPredicates.GET("/index"),
request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml))
.andRoute(RequestPredicates.GET("/s"),
request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(sHtml));
}
請注意上面的兩個文件, s.html
, index.html
都不在默認的靜態資源目錄下
III. 小結
文中給出了WebFlux的靜態資源訪問姿勢,與SpringMVC有一些區別
- url映射時,直接返回視圖名,會提示
Could not resolve view with name xxx
- 通過修改配置
spring.resources.static-locations
指定新的靜態資源目錄無效
在WebFlux中,推薦使用實現WebFluxConfigure
接口的方式,重寫addResourceHandlers
方法來自定義資源路徑映射
也可以針對單獨的靜態資源,借助@Value
來手動路由
II. 其他
0. 項目
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源碼:https://github.com/liuyueyi/spring-boot-demo/blob/master/spring-boot/200-webflux
1. 一灰灰Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰Blog個人博客 https://blog.hhui.top
- 一灰灰Blog-Spring專題博客 http://spring.hhui.top