本文介紹了每條url路徑和子路徑的Spring Single頁面/a/**=>;/a/index.html/a/靜態/**&qot;除外的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在構建Spring網站,該網站在子路徑下有反應單頁應用程序,我當前的URL結構應該如下所示
localhost/admin/** => react app
localhost/** => spring thymeleaf/rest/websocket app for everything else
react app mapping:
localhost/admin/static/** => static react files
localhost/admin/** => react index.html for everything else
Example of project resources structure:
resources/
admin/ <= my admin react files is here
index.html
static/ <= react css, js, statics
templates/ <= thymeleaf templates
static/ <= theamleaf static
...
因此,我需要為每個URL路由及其子路由轉發REACTIONindex.html
文件。除靜態文件外,基本上只有一個頁面的應用程序
看起來像是一項常見的任務,下面是我已經嘗試過的一些方法:
項目的完整工作演示Spring+Reaction+Gradle如何構建項目以及為什么我不能將Reaction文件放在不同的目錄(例如/Resources/Static):https://github.com/varren/spring-react-example
無法使用forward:/admin/index.html
for/admin/**
,因為這將創建遞歸,因為admin/index.html
也在admin/**
下,必須以某種方式截取admin/static/**
。
無法在WebMvcConfigurerAdapter
中使用addResourceHandlers
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/admin/**")
.addResourceLocations("classpath:/admin/");
}
index.html
僅映射到/admin/index.html
url,此選項幾乎有效,但僅當您從localhost/admin/index.html
訪問Reaction應用程序時
看到this和this和this和許多其他鏈接,我也有一些解決方案,但可能有一些通用選項我就是看不到
推薦答案
現在我正在使用自定義ResourceResolver
來解決此問題
演示:https://github.com/varren/spring-react-example
@Configuration
public class BaseWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceResolver resolver = new AdminResourceResolver();
registry.addResourceHandler("/admin/**")
.resourceChain(false)
.addResolver(resolver);
registry.addResourceHandler("/admin/")
.resourceChain(false)
.addResolver(resolver);
}
private class AdminResourceResolver implements ResourceResolver {
private Resource index = new ClassPathResource("/admin/index.html");
@Override
public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
@Override
public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, locations);
if (resolvedResource == null) {
return null;
}
try {
return resolvedResource.getURL().toString();
} catch (IOException e) {
return resolvedResource.getFilename();
}
}
private Resource resolve(String requestPath, List<? extends Resource> locations) {
if(requestPath == null) return null;
if (!requestPath.startsWith("static")) {
return index;
}else{
return new ClassPathResource("/admin/" + requestPath);
}
}
}
}
這篇關于每條url路徑和子路徑的Spring Single頁面/a/**=>;/a/index.html/a/靜態/**&qot;除外的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,