html - 当我使用 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。
这是结构:
- 源代码
- 主要的
- 资源
- 静止的
- css
- “我的 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>
运行项目后,谷歌浏览器不会加载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
应用程序根目录中的任何内容。
因此,用于通过 Thymeleaf 获取 CSS 的 URL 应该是/css/styles.css
.
像这样编辑您的 HTML 文件:
<link rel="stylesheet" type="text/css" href="../static/css/styles.css" th:href="@{/css/styles.css}">
在您的安全配置中,也使用/css
and 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
推荐阅读
- optimization - 在运行时通过常数优化模数
- sql - 在 oracle 中通过 Prior 子句查找没有 Connect by Prior 子句的给定员工的上级经理
- entity-framework - 使用 EF 将更改存储在数据库中
- javascript - React Draft 所见即所得不会加载 CSS 样式
- c# - Xamarin 表单 - 如何使用 sql server web api 上传和检索图像
- html - 在 css 中使用 translate 属性时文本变得模糊
- android - Razorpay android SDK 集成问题
- angular - 将ng2-translate与jhipster一起使用,属性“解析器”在“TranslateService”类型中是私有的,但在“TranslateService”类型中不是私有的
- html - 从文本转换中排除某些单词大写
- node.js - 尝试通过 React 访问 Redis:无法解析“hiredis”