Sar*_* DN 6 html resources spring static thymeleaf
我是Spring 的新手,我正在尝试制作一个漂亮的 Web 应用程序,到目前为止我设置了所有内容,如果我在浏览器上运行我的页面,它会按预期显示。但是,如果我在端口8080上使用 tomcat 运行它(我使用的是 Intelijj),它不会加载css和js文件,甚至不会加载图片。
我从字面上搜索了这个问题并打开了所有StackOverflow类似的问题,我尝试编写一个配置文件,但它没有做任何事情,我对这种方法不确定,因为我见过有人没有写任何配置的例子,但他们仍然设法使所有静态资源加载,等等。是否需要编写一些秘密的应用程序属性?或者有必须写的配置代码?
我的资源文件夹如下所示:
-resources
-static
-CSS
-things.css
-JS
-datepicker.js
-Images
-many pictures
-templates
-Home.html and other pages
Run Code Online (Sandbox Code Playgroud)
而我之前引用 static-CSS-things.css 的代码是这样的:
link href="../static/CSS/things.css" th:href="@{/CSS/things.css}" rel="stylesheet" media="all" type="text/css"
Run Code Online (Sandbox Code Playgroud)
我认为这会使我的 css 文件加载,但事实并非如此。js 和图片也一样。谢谢!
Gui*_*ira 18
确保您的 css 和 js 文件采用以下结构:
src/main/resources/static/css/things.css
src/main/resources/static/js/things.js
确保您从位于 src/main/resources/templates 中的 spring boot 模板文件夹下的页面调用静态资源
始终使用 thymeleaf 标记引用您的资源,因为这样无论您运行应用程序的端口如何,它都将始终正确加载。
src/main/resources/templates/example.html
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<!-- CSS -->
<link th:href="@{/css/things.css}" rel="stylesheet"></link>
<!-- JS -->
<script th:src="@{/js/things.js}" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果仍然无法正常工作,请尝试使用 Google Chrome 中的检查,转到“网络”选项卡并检查从您的 css 和 js 文件返回的错误,然后在此处发表评论。
假设您在 static 文件夹下有 css 和 js 文件夹,然后像这样使用它 -
<link href="css/custom.css" rel="stylesheet">
<script src="js/custom.js"></script>
Run Code Online (Sandbox Code Playgroud)
你可能也想看看这些 -
https://www.springboottutorial.com/spring-boot-with-static-content-css-and-javascript-js https://www.baeldung.com/spring-mvc-static-resources
值得注意的是,确保您有适当的 thymeleaf 依赖项和标签。