- 静态资源访问失效,是应为其地址无法自动添加项目路径
以下model.html
<div th:fragment="header" >
头部
</div>
<div th:fragment="footer" >
尾部
</div>
以下index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- 如果使用了base标签,就会自动给静态资源加上上下文路径(项目路径),就不需要加@{},两种方法选一样 -->
<!-- <base th:href="@{/}"> -->
<meta charset="UTF-8">
<title>Title</title>
<!-- 使用 th:href="@{样式路径}" 给静样式 url 添加项目上下文路径 -->
<link th:href="@{css/style.css}" rel="stylesheet" />
</head>
<body>
<!-- 头部 th:include 格式(【url】 :: 【url对应页面的 th:fragment="header"】) -->
<div th:include="model :: header"></div>
<!--
以下内容在springboot项目打包成war包部署在tomcat后,
如果配置项目路径,
所有静态资源以及a标签的url不会自动加上此项目路径。
因此,会导致页面故障,
加上 thymeleaf 技术能解决问题。
-->
<div>
<h1 th:text="${text}">后台传过来的文本</h1>
<!-- 使用 th:src="@{页面路径}" 给 url 添加项目上下文路径 -->
<iframe th:src="@{index_1}" style="width: 500px"></iframe>
</div>
<!-- 脚部 th:include 格式(【url】 :: 【url对应页面的 th:fragment="header"】) -->
<div th:include="model :: footer"></div>
<!-- 使用 [[@{/}]] 取得上下文路径 context -->
<script type="text/javascript" th:inline="javascript"> var context = [[@{/}]]; </script>
<script type="text/javascript">
console.log(context)
</script>
</body>
</html>
以下index_1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link th:href="@{css/style.css}" rel="stylesheet" />
</head>
<body>
<h1 th:text="${text}">后台传过来的文本</h1>
</body>
</html>
以下controller.java
package com.example.templates;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class controller {
@GetMapping("/")
public String conIndex(Model model){
model.addAttribute("text","index:这是后台传来的文本");
return "index";
}
@GetMapping("/index_1")
public String index_1(Model model){
model.addAttribute("text","index_1:这是后台传来的文本");
return "index_1";
}
@GetMapping("/model")
public String model(){
return "model";
}
}
- 结果