Thymeleaf,IntelliJ和Spring Boot无法正确加载CSS文件 [英] Thymeleaf, IntelliJ and Spring Boot not loading CSS files correctly
问题描述
我一直遇到这个问题,每次,我只能通过创建一个看起来有效的新项目来解决它.这次我打算找出为什么会发生这种情况,或者我经常遇到这种情况.CSS文件以HTML文件的形式加载到服务器中,当我打开并带有相对路径时,它们以HTML文件打开
I have been experiencing this issues and each time, I only resolve it by creating a new project which appears to work. This time I intend to find out why this happens or I encounter it this often. CSS files get loaded into the server as HTML files and when I open then with the relative path, they open as HTML
位于template/index.html
Index file located under templates/index.html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<link type="text/css" th:href="@{/css/styles.css}" href="../static/css/styles.css"
rel="stylesheet" />
</head>
<body>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery.js}"></script>
</body>
</html>
这是我的CSS文件,位于resources/static/css/styles.css
This is my CSS file which is located under resources/static/css/styles.css
body {
color: blue;
}
我在类路径上具有Spring安全性,因此我将安全性配置为此
I have Spring security on my classpath so I configured security as this
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/webjars/**",
"/static/**"
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated()
.and().formLogin();
}
}
我不明白为什么浏览器会这样加载
I do not understand why the browser loads up as such
似乎所有资源都根据网络状态成功加载
Seems like all resources are loaded successfully according to the network status
当我单击styles.css时,这是调试器中的输出.我不知道为什么
When I click on the styles.css, this is the output in the debugger. I don't know why
在我再次启动一个新项目之前,请多多帮助.谢谢
Any Help is much appreciated before I start up a new Project again. Thank you
推荐答案
经过一系列测试以产生此问题,我能够解决该问题.当我将映射保留为常规状态时(例如允许我的控制器直接映射到根映射),就会出现问题.
I was able to solve the problem after a series of test to produce this problem. The problem arises when I leave my mappings general as in allowing my controller to map directly to the root mapping.
示例是
@GetMapping // Here is the problem... This was the only method in the controller
public String home() {
return "index";
}
我通过设置类似的映射来解决此问题
I fixed this by setting a mapping like
@GetMapping(value= "/")
public String home() {
return "index";
}
或通过使用类级别映射
@RequestMapping(value= "/")
public class Controller {
public String home() {
return "home";
}
}
这篇关于Thymeleaf,IntelliJ和Spring Boot无法正确加载CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!