【问题标题】:How to load an image in spring boot with thymeleaf?如何使用 thymeleaf 在 Spring Boot 中加载图像?
【发布时间】:2021-04-24 02:59:17
【问题描述】:

我只想在 Spring Boot 应用程序的 html 文件中显示图像。

但由于某种原因,我无法让它在一个特定的应用程序中工作。

我说“一个特定的应用程序”是因为我可以让它在另一个应用程序中以完全相同的方式工作。

原来是这样的:

将 tempLogo.jpg 放入文件夹/src/main/resources/static/images

在 src/main/resources/templates/home.html:

<img src="images/tempLogo.jpg"></br>
<img src="/images/tempLogo.jpg"></br>
<img th:src="@{/images/tempLogo.jpg}"></br>
<img th:src="@{images/tempLogo.jpg}"></br>

这些都不适用于 app1。 所有这些都在 app2 中使用相同的代码和路径工作。

有趣的是,在 app1 中我可以成功访问 /static 文件夹中的 .css 和 .js 文件,如下所示:

<link rel="stylesheet" type="text/css" href="/css/styles.css"/>
<script src="/scripts/scripts.js"></script>

这些位于:

/src/main/resources/static/css

/src/main/resources/static/scripts

不知道发生了什么,就像我说的,在 app2 中具有相同的确切路径和代码。

【问题讨论】:

  • 您的代码似乎没问题,可能是文件名中的拼写错误?另外,使用 th:src 时会生成什么 URL?
  • 找不到任何错字。这是 th:src 生成的内容:&lt;img src="/images/tempLogo.jpg"&gt;&lt;/br&gt; &lt;img src="images/tempLogo.jpg"&gt;&lt;/br&gt;
  • &lt;img th:src="@{/images/tempLogo.jpg}"&gt; 是要走的路。在您的帖子中,您说您将 img1.jpg 放在文件夹中,但该行引用 tempLogo.jpg。你们有没有可能把两者搞混了?
  • 没有。我在代码中只使用了 tempLogo.jpg。就在我称之为img1的问题中。我将更新问题以使其正确。
  • 我现在在 STS 中运行了一个干净的项目,它成功了!似乎有一些未知的垃圾对此产生了影响。

标签: html spring spring-boot thymeleaf


【解决方案1】:

经过一番挖掘,发现问题是没有为图像文件夹启用 Spring 安全性。所以在扩展 WebSecurityConfigurerAdapter 的类的 configure 方法中添加了web.ignoring().antMatchers("/images/**");,它就起作用了。

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");      
        web.ignoring().antMatchers("/scripts/**");
        web.ignoring().antMatchers("/images/**");
    }

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 2017-07-26
    • 2016-04-11
    • 1970-01-01
    • 2019-09-27
    • 2015-03-08
    相关资源
    最近更新 更多