SpringBoot+Thymeleaf中静态资源css、js等的引用问题

SpringBoot + Thymeleaf项目中静态资源的引用问题是非常常见的问题,也是最头疼的问题,其实一点儿也不难,只是有几个问题没注意到始终无法解决。

1、静态资源的位置

1.1、 在SpringBoot项目运行的时候,引用静态资源需要使用Thymeleaf.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <link rel="stylesheet" href="../static/css/bootstrap.css" th:href="@{/css/bootstrap.css}">
</head>

没有Thyemeleaf不能引用。

1.2、静态资源在没有配置位置的时候默认是在resources/static目录中的

项目目录如下

静态资源默认目录是resources/static,因此在这里引用静态资源需要如下写:

<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <link rel="stylesheet" href="../static/bootstrap/css/bootstrap.css" th:href="@{/bootstrap/css/bootstrap.css}">
</head>

1.3、还可以在配置文件中指定静态资源所在的位置

在application.properties配置文件中:

spring.resources.static-locations=classpath:static/bootstrap

设置静态资源所在位置为resources/static/bootstrap.

此时,HTML中引用静态资源就该这么写:

<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <link rel="stylesheet" href="../static/bootstrap/css/bootstrap.css" th:href="@{/css/bootstrap.css}">
</head>

2、不能引用最可能的原因

SpringBoot项目的所有文件都必须要编译到target文件夹下才能运行,因此首先检查你的target目录下有没有静态资源。

如果这里根本就没有静态资源,自然肯定不能引用了。

是什么原因导致target/classes文件夹下没有静态资源的呢?

最可能的原因就是在项目的pom文件中,你没有指明要将.css、.js等这些文件编译进target文件夹中。必须要申明,这些文件才会被正确编译进去。

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.yml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

这里申明了,resources目录下,**/*.*类型的文件将被编译进target/classes文件夹,也即是所有的文件,因此.css和.js类的文件就可以正确的编译进去。

如果改成如下这样:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.yml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.yml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

代表只将resources下的.properties文件、.xml文件、.yml文件编译进去target/classes文件夹,自然就没有静态资源了,就没法引用了。编译得到的target文件夹如下:

可以看到,按照如上pom文件,编译得到的target/classes文件夹下根本就没有静态资源,不可能引用成功。

3、注意

3.1、每次修改pom文件后都运行一下,否则不会更新,修改的效果看不到

3.2、每次编译时先maven clean一遍,否则上一次产生的文件可能会影响到这一次,让你找不到真正的原因

猜你喜欢

转载自blog.csdn.net/qq_27198345/article/details/111343238