提问者:小点点

当我用百里香运行我的Spring Boot项目时,浏览器不会加载css文件,但是href和th:href的路径是正确的


所以我读了很多关于我的问题的文章和线索,比如:

拒绝应用样式,因为其MIME类型(“application/json”)不受支持

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

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

目前的情况是:

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

结构如下:

  • 钢筋混凝土<ul>
  • 主要的,主要的<ul>
  • 资源<ul>
  • 静态的,静态的<ul>
  • css格式<ul>
  • “我的css文件”
  • “我的html文件”

这是我的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>

在运行项目后,谷歌chrome不会加载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文件的预览功能,它实际上是有效的。

如果有人能帮忙并感谢你,那就太好了!

来自德国的问候


共1个答案

匿名用户

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}">

在您的安全配置中,也使用< code>/css而不是< code>/static/css:

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

您也可以使用:

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

PathRequest.to静态资源()。