spring4推荐使用thymeleaf模板进行开发,刚好最近需要使用,一起来学习一下
1.加入maven依赖
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.简单配置application.yml
spring:
thymeleaf:
mode: LEGACYHTML5
prefix: classpath:/templates/
suffix: .html
cache: false
encoding: utf-8
3.编写html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<META HTTP-EQUIV="expires" CONTENT="0">
<head th:fragment="head">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>title</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<link rel="icon" href="favicon.ico">
<link rel="stylesheet" th:href="@{/layui/css/layui.css}">
<link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" />
<link rel="stylesheet" media="all" th:href="@{/css/main.css}"/>
<script src="" th:src="@{/js/jquery-1.8.0.min.js}"></script>
<script type="text/javascript">
var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/";
</script>
</head>
<body>
</body>
</html>
我这里写的是一个简单的公共的html用到了th:fragment="head"用来定义用于加载的块,在我们需要使用的页面使用
<head th:replace="header :: head">就可以替换head标签里的内容,当然还可以使用th:include
th:include 和 th:replace的区别
th:include和th:replace都可以引入模块,两者的区别在于
th:include:引入子模块的children,依然保留父模块的tag。
th:replace:引入子模块的所有,不保留父模块的tag。
在js中还写了一串js代码,用来获取项目名
<script type="text/javascript"> var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/"; </script>
这样的话需要在调后台服务的地方拼写WEB_ROOT就不用担心把路径搞错了
4.编写controller
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/toIndex")
public String toIndex(){
return "index";
}
}
在controller里面返回视图就可以了

本文详细介绍了如何在Spring4项目中整合Thymeleaf模板引擎,包括Maven依赖配置、application.yml设置、HTML编写技巧及Controller实现。
672

被折叠的 条评论
为什么被折叠?



