springboot+thymeleaf中靜態檔案獲取失敗問題
阿新 • • 發佈:2020-12-22
技術標籤:Error Conllection
遇到的問題:使用springboot和thymeleaf搭建的一個小demo,訪問login.html時出現了獲取不了login.css和login.js檔案的問題
<!--login.html檔案-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
< meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel=" stylesheet" th:href="@{/css/login.css}">
<script type="text/javascript" th:src="@{/js/login.js}"></script>
</head>
<body>
<p>Hello!This is login.html</p>
</body>
</html>
在application.properties配置檔案中應當寫一些必要的配置:
#靜態檔案配置
spring. resources.static-locations=classpath:/static/
但是它在我的IDEA中顯示的是這樣的:
這表示這行程式碼是無效的,至於為什麼無效,沒有去深究,總之我們需要另闢蹊徑。
我們可以建立一個config類來做配置:
@Configuration
public class WebMvcConfigStatic extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
重新部署訪問,問題就解決了!