【问题标题】:Thymeleaf, IntelliJ and Spring Boot not loading CSS files correctlyThymeleaf、IntelliJ 和 Spring Boot 无法正确加载 CSS 文件
【发布时间】:2018-08-31 10:24:29
【问题描述】:

我一直遇到这个问题,每次我只通过创建一个似乎可以工作的新项目来解决它。这次我打算找出为什么会发生这种情况,或者我经常遇到这种情况。 CSS 文件作为 HTML 文件加载到服务器中,当我使用相对路径打开时,它们以 HTML 格式打开

位于 templates/index.html 下的索引文件

  <!DOCTYPE html>
    <html lang="en"
           xmlns="http://www.w3.org/1999/xhtml"
           xmlns:th="http://www.thymeleaf.org">
     <head>
            <meta charset="UTF-8" />
            <title>Title</title>
            <link type="text/css" th:href="@{/css/styles.css}" href="../static/css/styles.css"
                  rel="stylesheet" />
        </head>
        <body>

    <script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/jquery.js}"></script>

    </body>
    </html>

这是我的 CSS 文件,位于 resources/static/css/styles.css 下

body {
    color: blue;
}

我的类路径上有 Spring 安全性,因此我将安全性配置为这样

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/webjars/**",
            "/static/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll()
                .anyRequest().authenticated()
                .and().formLogin();
    }
}

我不明白为什么浏览器会这样加载

根据网络状态,好像所有资源都加载成功了

当我单击styles.css 时,这是调试器中的输出。不知道为什么

在我再次启动新项目之前,非常感谢任何帮助。谢谢

【问题讨论】:

    标签: html css spring intellij-idea thymeleaf


    【解决方案1】:

    经过一系列测试产生了这个问题,我能够解决这个问题。 当我让我的映射保持一般性时,问题就出现了,因为允许我的控制器直接映射到根映射。

    例子是

    @GetMapping // Here is the problem... This was the only method in the controller
    public String home() {
      return "index";
    }
    

    我通过设置类似的映射解决了这个问题

    @GetMapping(value= "/")
    public String home() {
       return "index";
    }
    

    或通过使用类级别映射

    @RequestMapping(value= "/")
    public class Controller {
    
       public String home() {
         return "home";
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 2019-06-07
      • 2017-03-20
      • 1970-01-01
      • 2020-08-16
      • 2016-04-20
      • 1970-01-01
      • 2018-12-07
      • 2017-06-14
      相关资源
      最近更新 更多