首先要说的是,我一直在寻找解决方案,现在我非常绝望。
当由 Spring Boot 运行时,我无法从 html 页面访问 css 文件。
html.文件
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head lang="en">
<title th:text='#{Title}'>AntiIntruder</title>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}" />
</head>
<body>
...
应用程序.java
@SpringBootApplication // adds @Configuration, @EnableAutoConfiguration, @ComponentScan
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/*");
}
}
文件夹结构:
我试过将 css
文件夹放入 static
文件夹和/或删除 addResourcesHandlers,通过相对路径和其他一些东西引用 css。似乎没有什么可以解决这个问题。
如果您尝试解决此问题但没有找到解决方案,也请告诉我,以便我知道我没有被忽略。
最佳答案
<强>1。使用自定义资源路径
在你的网络配置中
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/assets/**")) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
}
}
将您的style.css
文件放入此文件夹
src/main/resources/assets/css/
在你看来之后
<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />
.
<强>2。在 spring boot 中使用预定义路径
从您的网络配置中删除 addResourceHandlers
将 style.css
放入以下任意文件夹
src/main/resources/META-INF/resources/assets/css
src/main/resources/resources/assets/css/
src/main/resources/static/assets/css/
src/main/resources/public/assets/css/
在 View 中
<link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" />
.
注意:您可以在此处删除 assets
文件夹。如果您想这样做,请将其从预定义的资源文件夹以及 View th:href
中删除。但我保持原样,因为您在问题中明确提到了 assets/
路径。所以我相信您需要在您的资源 URL 中包含 assets/
。
关于java - 带有 Thymeleaf 的 Spring Boot - 找不到 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562471/