gpt4 book ai didi

css - 将 Spring 中的样式表与 Thymeleaf 链接时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:57 25 4
gpt4 key购买 nike

所以我已经为此苦苦挣扎了一段时间,但仍然无法弄清楚。

我无法使外部 CSS 文件正常工作,浏览器总是给我一个 200 成功消息,但文件从未加载。

我尝试了很多不同的方法,但目前情况是这样的:

在 HTML 文件中链接:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Tourverwalter</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" th:href="@{/assets/css/myStyle.css}" />
</head>

CSS 文件:

body {
background-color: lightblue;
text-align: center;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
width: 20%;
cursor: pointer;
}

header{
vertical-align: top;
}

.container {
width: 75%;
height: 30px;
padding: 10px;
}

.left {
width: 40%;
height:30px;
float: left;
}

.right {
margin-left: 60%;
height: 30px;
}

WebMcvConfig 文件:

package ese4.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");

}

}

文件夹层次结构: Folder Hierarchy

最佳答案

如果您使用的是 Spring Boot,我建议您将结构更改为:

src/main/resources/static/css

然后您可以删除重写的 addResourceHandlers 方法。 Spring Boot will use the static folder to serve your static content .

然后你会更新你的链接:

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

旁白:您还需要包含 css 的 href 路径,这样当您在没有加载 Spring Boot 的情况下在浏览器中打开文件时,您仍然可以看到 CSS 的效果。这是使用 Thymeleaf 的一个巨大优势,因为您的 UI 人员无需了解 Java 或 Spring 即可查看格式化页面。

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

最后,您的其他方法可以简化为:

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

关于css - 将 Spring 中的样式表与 Thymeleaf 链接时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47591254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com