gpt4 book ai didi

java - 如何在 Spring Boot 2.2.6 中提供静态内容?

转载 作者:行者123 更新时间:2023-12-02 08:40:56 24 4
gpt4 key购买 nike

我是 Springboot 的新手,我正在尝试在其根(localhost:8080)路径上显示 html 页面。为此,我用谷歌搜索并浏览了 -

  1. Spring Boot not serving static content
  2. https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
  3. Spring Boot app not serving static content
  4. Springboot does not serve static content

尝试了几乎所有方法,但没有一个对我有用。

确切的问题

如果任何资源/(静态/或公共(public)/或meta-inf/资源)内没有index.html文件,则可以正常工作并显示一些Spring数据剩余的列表。如果我创建一个 index.html 文件,那么它会给出一个 404 错误,没有 @EnableWebMvc 注释,如果使用 @EnableWebMvc 那么它显示 Spring data Rest api 列表。

除了index.html文件之外,它在根路径中显示Spring data api的列表,并且除了index.html之外的url(localhost:8080/test.html)也有同样的问题。

通过使用此配置实现 public class StaticResourceConfiguration Implements WebMvcConfigurer,此问题不会产生任何影响。

最佳答案

simple spring boot initializer 开头

...我们可以将静态 (html) 文件放入以下位置之一:

  • (src/main/resources:)
  • 静态
  • 资源
  • 公开
  • 元信息文件
    • 资源

这会产生默认(类路径)位置,通过 spring.resources.static-locations 属性进行配置。

这些将通过 spring.mvc.static-path-pattern-property ( ref ) 的值公开,默认情况下:/**

因此,可以通过以下位置访问上述文件夹之一中具有默认配置的静态 index.html 文件:

因此:http://localhost:8080/test.html 没有问题...

<小时/>

结账 at github .

所以这至少回答了“问题标题”“如何在 springboot 2.2.6 中提供静态内容?”。

<小时/>

spring.resources.static-locations的顺序出现(index.html首选来自META-INF/resources)也是静态文件位置的“优先级”(从左到右) ,第一场比赛获胜)。

<小时/>

当我们添加@EnableWebMvc

...“一切都会被破坏”(上下文加载,但是):

WARN ... o.s.web.servlet.PageNotFound             : No mapping for GET /
WARN ... o.s.web.servlet.PageNotFound : No mapping for GET /index.html
WARN ... o.s.web.servlet.PageNotFound : No mapping for GET /test.html

..请考虑这一点:why spring-boot application doesn't require @EnableWebMvc

使用“非默认配置”,您必须提供更多详细信息,才能找到特定的解决方案。

但是对于“Springboot 新手”:从初始化器开始,“默认值”听起来是最佳选择!从这里开始,您可以根据工作配置重新优化您的配置。

<小时/>

如果您出于某种原因想要/需要 @EnableWebMvc 注释,这将再次导致“以前的”行为/恢复 (2.2.6) 默认值静态内容处理:

@EnableWebMvc
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/");

}

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}

(假设与现有配置/资源处理程序没有冲突)

关于java - 如何在 Spring Boot 2.2.6 中提供静态内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61393769/

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