【问题标题】:How to make Spring Boot see my images from resources如何让 Spring Boot 从资源中看到我的图像
【发布时间】:2017-12-29 03:43:44
【问题描述】:

嗨,我在资源/静态中有这样的图像并将它们放入我的 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>Test</title>

</head>
<body>
<div>
    <form method="POST" enctype="multipart/form-data" action="/">
        <p>
            <img src="../static/image1.png" alt="Image 1"/>
            <img src="../static/image2.png" alt="Image 2"/>
            <tr>
                <td></td>
                <td><input type="submit" value="Test"/></td>
            </tr>
        </p>
    </form>
</div>

<div th:if="${success}">
    <img src="/static/result.png"/>
</div>

</body>
</html>

然后,在 ResourceConfig 中

@Configuration
@EnableWebMvc
@ComponentScan
public class ResourceConfig extends WebMvcConfigurerAdapter {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/images/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }
}

问题是,该应用程序看不到我的图像。我添加了资源处理程序,但它没有奏效。输出是

Output

【问题讨论】:

  • 您能否提供浏览器的控制台日志?您是否看到应用程序记录的任何错误?
  • 只是错误 404,localhost:8080 找不到这个图像。我意识到了,但是为什么看不到我的图像?

标签: java html spring spring-boot


【解决方案1】:

html 模板中的这一行

<div th:if="${success}">

让我觉得您正在使用 Thymeleaf 作为您的模板引擎。如果是这种情况,您应该使用它来引用静态内容:

<img th:src="@{/result.png}"}/>

如果您的 png 文件确实位于静态文件夹的根目录中。

【讨论】:

    【解决方案2】:

    @Override 方法 addResourceHandlers 显示 Spring Framework 中的所有静态资源在哪里。所以...您的包含图像的文件夹也是静态资源必须在您的根静态资源处理程序下。像这样设置并在你的项目中的 WebContent 文件夹下创建这个文件夹。

    @Override
        public void addResourceHandlers(final ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
        }
    

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 2017-06-01
      • 2020-03-01
      • 2020-01-03
      相关资源
      最近更新 更多