SpringBoot+Thymeleaf中静态资源css、js等的引⽤问题
⽂章⽬录
SpringBoot + Thymeleaf项⽬中静态资源的引⽤问题是⾮常常见的问题,也是最头疼的问题,其实⼀点⼉也不难,只是有⼏个问题没注意到始终⽆法解决。
1、静态资源的位置
1.1、在SpringBoot项⽬运⾏的时候,引⽤静态资源需要使⽤Thymeleaf.
<!DOCTYPE html>
<html lang="en"th="">
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet"href="../static/css/bootstrap.css"href="@{/css/bootstrap.css}">
</head>个人网站排版
没有Thyemeleaf不能引⽤。
1.2、静态资源在没有配置位置的时候默认是在resources/static⽬录中的
项⽬⽬录如下
静态资源默认⽬录是resources/static,因此在这⾥引⽤静态资源需要如下写:
<head>
matlab ceil<meta charset="UTF-8">python基础题目及答案
socket语句<title>Home</title>
<link rel="stylesheet"href="../static/bootstrap/css/bootstrap.css"href="@{/bootstrap/css/bootstrap.css}">
</head>
1.3、还可以在配置⽂件中指定静态资源所在的位置
在application.properties配置⽂件中:
设置静态资源所在位置为resources/static/bootstrap.
此时,HTML中引⽤静态资源就该这么写:
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet"href="../static/bootstrap/css/bootstrap.css"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>一个函数没有prototype什么意思
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>true</filtering>
properties是什么文件
</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⼀遍,否则上⼀次产⽣的⽂件可能会影响到这⼀次,让你不到真正的原因