当我使用 Thymeleaf 运行我的 Spring 启动项目时,浏览器不会加载 css 文件,但 href 和 th:href 的路径是正确的



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

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

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

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

目前的情况是:

我有一个使用thymelaf的Spring Boot项目,在resources/templates下有一个html文件,在resssources/templates/css下也有一个css。

结构如下:

  • src
    • main
      • 资源
        • 静态
          • css
            • "我的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>

运行项目后,googlechrome不会加载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文件的预览功能,它确实有效。

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

来自德国的问候

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

因此,使用Thymelaf获取CSS的URL应该是/css/styles.css

编辑你的HTML文件如下:

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

在您的安全配置中,也使用/css而不是/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

最新更新