java - 如何为特定路径重定向到 404 上的默认资源文件
问题描述
我正在将单页应用程序集成到 Spring Boot 项目中。UI (SPA) 的上下文是http://localhost:8080/ui/
Spring Boot 应用程序本身的上下文是http://localhost:8080/。控制器具有与 UI 上下文无关的不同上下文。
有一种情况是 UI 将浏览器地址行更改为服务器不知道的 URL,但不向服务器发送请求。在这样的事情之后,如果我刷新页面,服务器会以 404 响应。但是我需要返回默认的 index.html 页面。
示例:我转到http://localhost:8080/ui/,UI 将其更改为http://localhost:8080/ui/mainpage。我刷新页面并得到 404。
我发现了类似的问题,但我想做点不同的,然后在那里回答。
当有对http://localhost:8080/ui/ **的请求时,我需要返回默认资源(index.html),如果向http://localhost:8080/context1/blablabla发出请求,我想返回 404。
在调试和谷歌搜索后,我提出了下一个解决方案:
@Configuration
public static class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/ui/**")
.addResourceLocations("/ui/")
.resourceChain(false)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource resource = super.getResource(resourcePath, location);
return Objects.isNull(resource) ? super.getResource("index.html", location) : resource;
}
});
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ui/").setViewName("index.html");
}
}
这里的做法是手动添加PathResourceResolve并覆盖它的getResource方法,所以当resource为null时,调用index.html资源。这样,我可以确保仅在向http://localhost:8080/ui/ ** 发出请求时返回默认页面,并且所有其他请求将照常返回 404。
我认为这不是正确的解决方案,对我来说它看起来像 hack。我想也许资源处理程序有一些像默认资源这样的配置,但我没有找到任何关于它的东西。
我的问题是如何正确地做到这一点?感谢任何建议。
解决方案
推荐阅读
- installation - 与团队共享 Visual Studio 安装选项
- java - Cloud Config 服务器响应的 Java 模型
- django - Django 表单:我无法从主页访问表单
- sql - ORACLE:一键查看不同的日期范围
- php - Laravel 5.7 访问器,它基本上根据一些可能的匹配检查与 auth 用户的相关性
- java - 排序 Arrays.toString()
- ios - 在 MapKit 中显示用户位置所需的步骤
- python - 无法在我的虚拟环境中导入 Django
- firebase - Firebase Cloud Firestore 数据库规则数据访问被拒绝
- java - ListItem.onItemClickListener 与 CustomAdapter 无响应