需求:从后台控制器返回到success.html页面,success.html中只有该页面的主要内容部分(即不包括公共的部分),但是浏览器访问的时候显示的是完整的页面布局(即success.html页面中不仅有主要的内容部分,还包括公共部分)。
首先在pom.xml中引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在common路径下有一个主要的html页面layout.html,在layout中引入引入thymeleaf,代码如下:
layout.html页面引入了common/head.html页面
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.theamleaf.org">
<head>
</head><body>
<!-- 公共部分 start -->
<div th:include="common/head :: headbar"></div>
<!-- 公共部分 end --><!-- 被引入的部分 start -->
<div layout:fragment="maincontent"></div>
<!-- 被引入的部分 end --></body>
</html>
common/head.html页面:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"><body>
<div th:fragment='headbar'>
页头部分
</div>
</body>
</html>
主内容页面,例如success.html页面,要想在success.html中写Javascript并且被加载,需要在<script>标签中加上th:inline="javascript"
<!DOCTYPE html>
<!--
layout:decorator="common/layout"是引入common/layout.html页面,然后用success.html页面中的 layout:fragment="maincontent"部分替换common/layout.html页面中的<div layout:fragment="maincontent"></div>
-->
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.theamleaf.org" layout:decorator="common/layout">
<!-- begin::Head -->
<head><script type="text/javascript" th:inline="javascript">
// js代码
</script>
</head><body>
<div layout:fragment="maincontent">
成功页面
</div>
</body>
</html>
在后台请求success页面
@Controller
@RequestMapping(value="/")
public class HelloController {@GetMapping(value="/success")
public String success() {
return "success";
}
}
得到的页面就是:
<!DOCTYPE html>
<html>
<body>
<!-- 公共部分 start -->
<div>
页头部分
</div>
<!-- 公共部分 end --><!-- 被引入的部分 start -->
<div>
成功页面
</div>
<!-- 被引入的部分 end --></body>
</html>
返回的是一个完整的页面 (包括layout页面中的公共部分)