【问题标题】:Images in html for Spring thymeleaf won't show upSpring thymeleaf 的 html 中的图像不会显示
【发布时间】:2021-02-16 10:46:26
【问题描述】:

下面,我使用 login.html 作为在/static/images/ 中添加图像test.png 的页面

所以,在 login.html 中,我有 <img src="../static/images/test.png" width="1000" th:src="@{images/test.png}"/>,它给出了一个空白图像。为什么不显示?

在我的SecurityConfiguration.java 文件中,我有

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
      .csrf().disable()
      .authorizeRequests()
      //.antMatchers("/**").hasRole("ADMIN")
      .antMatchers("/static").permitAll()
      .and().formLogin()
      .loginPage("/login")
      .permitAll(); 

当我使用这个配置时,它使用默认的 index.html 页面,可以很好地显示图像。但是,如果我取消注释 .antMatchers("/**").hasRole("ADMIN"),它会将我带到 login.html,但我无法查看图像。

【问题讨论】:

  • 看起来不错..(新)资源可能没有被拾取...干净的构建可能会解决这个问题

标签: html spring thymeleaf


【解决方案1】:

我可以发现 3 个问题。

  1. 您应该使用.antMatchers("/images/**") 而不是.antMatchers("/static"),因为src/main/resources/static 中的任何内容都将从您的应用程序的根目录提供(如here 所解释的那样 - 请注意文件夹“public”和“static”可以互换Spring Boot)。
  2. .authorizeRequests() 的匹配器顺序很重要!就像method's documentation 的最后一个例子一样。你应该把你的蚂蚁匹配器颠倒过来:
   .antMatchers("/images/**").permitAll() // more detailed paths should go first
   .antMatchers("/**").hasRole("ADMIN")   // more general paths should go last
  1. 考虑使用th:src="@{/images/test.png}" 而不是th:src="@{images/test.png}"。开头的额外斜线使相对于应用程序根目录的路径与第一个建议一致。如Thymeleaf's documentation中所述:

以/ 开头的相对 URL(例如:/order/details)将自动以应用程序上下文名称作为前缀。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2014-08-06
    • 2013-04-09
    • 2017-06-25
    • 1970-01-01
    • 2023-01-02
    相关资源
    最近更新 更多