如何在春季用百里香叶添加静态资源

时间:2019-06-07 15:29:14

标签: html spring static resources 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

我以前引用static-CSS-things.css的代码如下:

link href="../static/CSS/things.css" th:href="@{/CSS/things.css}" rel="stylesheet" media="all" type="text/css"

我认为这会使我的css文件加载,但事实并非如此。 js和图片也一样。谢谢!

2 个答案:

答案 0 :(得分:3)

  1. 确保您的css和js文件具有以下结构:

    src / main / resources / static / css / things.css

    src / main / resources / static / js / things.js

  2. 确保从src / main / resources / templates中的spring boot template文件夹下的页面调用静态资源

  3. 始终使用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>

如果仍然无法使用,请尝试使用Google Chrome浏览器中的检查功能,进入“网络”标签,检查css和js文件返回了什么错误,然后在此处评论。

答案 1 :(得分:1)

假设您在静态文件夹下有css和js文件夹,然后像这样使用它-

<link href="css/custom.css" rel="stylesheet">
<script src="js/custom.js"></script>

您可能也想看看这些-

https://www.springboottutorial.com/spring-boot-with-static-content-css-and-javascript-js https://www.baeldung.com/spring-mvc-static-resources

值得注意的是,请确保您具有百里香依赖性和适当的标签。

相关问题