本文介绍了每条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;除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!