首页 > 解决方案 > 当我使用 Thymeleaf 运行 Spring Boot 项目时,浏览器不会加载 css 文件,但 href 和 th:href 的路径是正确的

问题描述

所以我阅读了很多关于我的问题的文章和主题,比如这些:

拒绝应用样式,因为它的 MIME 类型('application/json')不受支持

https://github.com/froala/angular-froala/issues/170

但没有一个答案能真正帮助我,所以我在问我自己的问题。

目前的情况是:

我有一个使用 thymeleaf 的 Spring Boot 项目,我在资源/模板下有一个 html 文件,我在 ressources/templates/css 下也有一个 css。

这是结构:

这是我的html文件:

<!DOCTYPE html>
<html lang="de" xmlns:th="http://www.thymeleaf.org">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Welcome to Mreza Mladih</title>
        <link rel="stylesheet" type="text/css" href="../static/css/styles.css" th:href="@{../static/css/styles.css}">
        <link href="https://fonts.googleapis.com/css2?family=Lato&family=Raleway&display=swap" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300&display=swap" rel="stylesheet">
    </head>

运行项目后,谷歌浏览器不会加载css文件:

拒绝应用来自...的样式

此外:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter  {    
@Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers(
                    "/registration**",
                    "/js/**",
                    "/static/css/**",
                    "/static/img/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/")
                    .permitAll()
                    .and()
                    .logout()
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login?logout")
                    .permitAll();
        }
}

有趣的是,我的 css 实际上是正确的并且有效!我使用 intellij 并且 IDE 具有 html 文件的预览功能,并且它确实有效。

如果有人可以帮助并感谢您,那就太好了!

来自德国的问候

标签: htmlcssspringthymeleaf

解决方案


Spring Boot 服务于src/main/resources/static应用程序根目录中的任何内容。

因此,用于通过 Thymeleaf 获取 CSS 的 URL 应该是/css/styles.css.

像这样编辑您的 HTML 文件:

<link rel="stylesheet" type="text/css" href="../static/css/styles.css" th:href="@{/css/styles.css}">

在您的安全配置中,也使用/cssand not /static/css

.antMatchers(
                    "/registration**",
                    "/js/**",
                    "/css/**",
                    "/img/**").permitAll()

您还可以使用:

http.authorizeRequests()
    .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
         .permitAll()
    .antMatchers("/registration**",
                 "/img/**")
        .permitAll()

PathRequest.toStaticResources().atCommonLocations()包括/css/*/js/*、和。/images/*_/webjars/*favicon.ico


推荐阅读