gpt4 book ai didi

spring-boot - 如何将 Spring Boot Web 应用服务器配置为服务器外部内容并使用默认资源目录?

转载 作者:行者123 更新时间:2023-12-04 10:58:54 27 4
gpt4 key购买 nike

我有一个小的 Spring Boot 应用程序,可以下载和提供内容。

一些上下文:复制和服务

该应用程序在灾难恢复盒上运行。它使用 spring 调度程序定期通过 rest api 从我们的 wiki/confluence 下载一组 html 页面,然后通过嵌入式 tomcat 提供这些相同的 .html 文件。

即,在主数据中心或数据库/等不可用的情况下,DR 数据中心可提供“说明”。

两把戏的小马。只需几行代码。谢谢 Spring !!!

使用 Spring Boot 提供外部内容

我得到了如何使用自定义 WebMvcConfigurer 从 Spring boot 提供外部内容的说明[见下面的代码]

但是丢失了默认的“免费”行为

添加自定义配置器“带走”所有“我免费获得的 url 映射内容”与 spring boot,例如自动使“/resources”目录作为 url 可供浏览器使用。例如“resources/styles/site.css”充当“http://localhost/styles/site.css

我确认:当我注释掉“WebMvcConfigurer”时,spring boot 的默认“url 映射到文件系统”行为按照文档工作。

问题

如何扩展 WebMvcConfigurer 以保留所有“免费”默认 spring 启动文件到 url 的映射,但添加外部映射,即告诉 tomcat 从该外部目录提供内容?

谢谢!

代码

@Configuration
@EnableWebMvc
@Slf4j
/**
* Exists to allow serving up static content from the filesystem
*/
class MvcConfig implements WebMvcConfigurer {

@Autowired
AppConfig appConfig

@Override
void addResourceHandlers(ResourceHandlerRegistry registry) {

registry
.addResourceHandler("/exported/**")
.addResourceLocations("file:${appConfig.outDir}/")

// I had to add this line to expose 'styles/' as a url path
registry.addResourceHandler("/styles/**")
.addResourceLocations("classpath:/public/styles/")



}

最佳答案

Spring MVC 默认从以下目录提供静态内容:

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"

但是,如问题中所示,WebMvcConfigurer 抑制了这些默认值,这就是为什么只提供在“外部”位置找到的文件的原因。

然而, addResourceLocations方法实际上支持字符串数组,因此您可以执行以下操作:

@Configuration
class StaticResourcesConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("file:///tmp/external-resources/",
"classpath:/static/");
}
}

现在,如果您输入 /tmp/html-external.htmlsrc/main/resources/static/html-internal.html然后(假设主机/端口是 localhost:8080 )两个请求都将被提供:
HTTP GET: http://localhost:8080/html-external.html
HTTP GET: http://localhost:8080/html-internal.html

当然,如果你有一些 Controller ,它们也可以工作

更新 1

根据评论,为了映射 http://localhost:8080/到一些预定义的 index.html :
  • 添加 src/main/resources/static/index.html
  • 修改WebMvcConfigurer如下:


  • @Configuration
    class StaticResourcesConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
    .addResourceLocations("file:///tmp/external-resources/",
    "classpath:/static/");

    registry.addResourceHandler("/")
    .addResourceLocations("classpath:/static/index.html");
    }
    }

    关于spring-boot - 如何将 Spring Boot Web 应用服务器配置为服务器外部内容并使用默认资源目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963232/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com