spring boot静态资源配置以及引入thymeleaf 模块(二)
1.pom.xml引入thymeleaf 模块
<!-- 引入 thymeleaf 模板依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.在resources文件夹下创建application.properties文件做如下配置
#关闭缓存及时刷新 #spring.freemarker.cache=false spring.thymeleaf.cache=true #热部署生效 spring.devtools.restart.enabled=true #设置重启目录,添加那个目录的文件需要的restart spring.devtools.restart.additional-paths=src/main/java #排除静态文件 spring.devtools.restart.exclude=static/**,public/** spring.devtools.restart.exclude=WEB-INF/** # 修改默认的静态寻址资源目录 #spring.resources.static-locations = classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ #设置静态文件路径css,js,图片等等 #spring.mvc.static-path-pattern=/static/** spring.mvc.static-path-pattern=/** spring.resources.add-mappings=true ############################################################ # # thymeleaf 静态资源配置 # ############################################################ spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # 关闭缓存,即时刷新,上线生产环境需要改为true spring.thymeleaf.cache=false
3.在SpringBoot中加载静态资源和在普通的web应用中不太一样。静态资源(js、css、图片等资源)默认目录位置需置于classpath下。
本例目录结构
4.这样我们就可以访问静态的图片了,spring.mvc.static-path-pattern=/**这个配置我们可以不用写static这个路径,如果是spring.mvc.static-path-pattern=/static/**我们就要加上statc这个路径
5.通过url来访问页面,展示静态资源
index.html代码
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> Thymeleaf模板引擎 <h1 th:text="${name}">hello world~~~~~~~</h1> <img alt="" th:src="@{/images/1.jpg}"></img> </body> </html>
index.html页面