在Thymeleaf模板引擎中,正确配置静态资源路径是Web开发的基础需求。本文将详细介绍如何让Thymeleaf链接表达式指向固定位置的静态资源。
Spring Boot默认的静态资源位置包括:
classpath:/static/classpath:/public/classpath:/resources/classpath:/META-INF/resources/使用@{}表达式引用静态资源:
<link th:href="@{/css/style.css}" rel="stylesheet" />
<script th:src="@{/js/app.js}"></script>
<img th:src="@{/images/logo.png}" alt="Logo" />
在application.properties中配置:
# 添加自定义目录
spring.web.resources.static-locations=classpath:/custom-static/,classpath:/static/
# 设置静态资源URL前缀
spring.mvc.static-path-pattern=/resources/**
如果需要引用外部或绝对路径的资源:
<!-- 使用完整URL -->
<link th:href="@{https://cdn.example.com/css/style.css}" rel="stylesheet" />
<!-- 或使用base标签 -->
<base th:href="@{${#httpServletRequest.contextPath}/}" />
使用资源版本化防止缓存问题:
<link th:href="@{/css/style.css(v=${@environment.getProperty('app.version')})}" rel="stylesheet" />
通过以上配置,您可以灵活地管理Thymeleaf中的静态资源引用,确保项目中的CSS、JavaScript和图片等资源能够正确加载。