我有一个Spring启动应用程序。现在我需要添加css。我在html文件中添加了一个css文件和它的链接。但由于某种原因,它不起作用。
我是这样做的。
将下面的 csstest.css 文件添加到 src/main/resources/static/css。
body {
background-color: blue;
}
h1 {
color: red;
margin-left: 20px;
}
添加了以下代码进行测试.html在 src/main/resources/templates。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/csstest.css"/>
</head>
<body>
<h1>This text should be styled, but it's not.</h1>
</body>
</html>
但是当我打开html页面时,没有应用css。为什么?
我看过一个教程,告诉他们在调度程序-servlet.xml上添加一个配置。但是我的应用程序是一个没有该文件的 Spring 启动应用程序。本教程不适用于 Spring 启动应用程序(这是我的情况)。Spring启动的教程没有告诉这样做。所以不确定是什么问题。
假设您的< code>@Configuration类扩展了< code > WebSecurityConfigurerAdapter ,请重写此方法。另外,不要忘记在配置类中使用注释< code>@EnableWebSecurity
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/css/**");
}
如果您希望spry-boot/thymeleaf检测与超文本标记语言文件相关的CSS文件,则必须使用thymeleaf表达式添加资源路径。
在超文本标记语言文件的头标记中包括以下内容-
<head>
<link rel="stylesheet" th:href="@{/css/YourCssFile.css}">
</head>
CSS不会被应用,因为他们没有在src/main/resources/templates/css下找到csstest.css文件。
您必须将test.html文件放在src/main/resources/static下才能指向src/main/resources/static/css下的csstest.css文件,因为这段代码在test.html
<link rel="stylesheet" type="text/css" href="css/csstest.css"/>
谢谢