The empty string can be resolved as index.html
in a custom ResourceResolver
. It is useful when deploying front-end services.
Here is an example:
String fallBack = "/index.html";
new ResourceResolver() {
@Override @NonNull
public Mono<Resource> resolveResource(ServerWebExchange exchange, @NonNull String requestPath, @NonNull List<? extends Resource> locations, @NonNull ResourceResolverChain chain) {
return chain
.resolveResource(exchange, requestPath, locations)
.switchIfEmpty(Mono.defer(()->chain.resolveResource(exchange, fallBack, locations)));
}
@Override @NonNull
public Mono<String> resolveUrlPath(@NonNull String resourcePath,@NonNull List<? extends Resource> locations,@NonNull ResourceResolverChain chain) {
return chain
.resolveUrlPath(resourcePath, locations)
.switchIfEmpty(Mono.defer(()->chain.resolveUrlPath(fallBack, locations)));
}
}
Its function is similar to that in nginx:
location / {
try_files $uri $uri/ @router;
}
location @router {
rewrite ^.*$ /index.html last;
}
Comment From: rstoyanchev
ResourceWebHandler
isn't really meant to serve HTML pages. In Spring MVC there is the ViewControllerRegistry
that lets you map a URL to an HTML view. There is no equivalent in WebFlux yet but you could use a simple controller:
@Controller
class ViewController {
@GetMapping
public String handle() {
return "/welcome.html";
}
}
Comment From: trionfordring
Thank you for your guidance.