前端模板引擎技术的出现,使得前端开发人员无需关注后端业务的具体实现,只关注自己的页面呈现效果即可。并且解决了前端代码错综复杂的问题,实现了前后端分离开发。SpringBoot框架对很多常用的模板引擎技术提供了整合支持,比如FreeMarker、Thymeleaf、Mustache等。SpringBoot不太支持JSP模板。
5.1 整合Thymeleaf
5.1.1 常用语法
在HTML页面上使用Thymeleaf标签,能够动态的替换掉静态内容,使页面静态展示。
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" media="all"href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" /><title>Title</title></head> <body><p th:text="${hello}">欢迎进入Thymeleaf学习</p></body></html>
上述代码中,“xmlns:th=”http://www.thymeleaf.org”用来引入Thymeleaf模板引擎标签,
关键字“th”标注标签是thymeleaf模板引擎提供的标签,以下是常用标签:
| th:标签 | 说明 |
|---|---|
| th:insert | 布局标签,替换内容到引入的文件 |
| th:replace | 页面片段包含(类似于JSP的include标签) |
| th:each | 元素遍历 |
| th:if | 条件判断,如果为真 |
| th:unless | 条件判断,如果为假 |
| th:switch | 条件判断,进行选择性匹配 |
| th:case | 条件判断,进行选择性匹配 |
| th:value | 属性值修改,指定标签属性值 |
| th:href | 用于设定链接地址 |
| th:src | 用于设定链接地址 |
| th:text | 用于指定标签的文版内容 |
标准表达式:
| 说明 | 表达式语法 |
|---|---|
| 变量表达式 | ${…} |
| 选择变量表达式 | *{…} |
| 消息表达式 | #{…} |
| 链接URL表达式 | @{…} |
| 片段表达式 | ~{…} |
5.1.2 基本使用
首先引入Thymeleaf的启动依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
在配置文件中进行配置
#启动模板缓存,默认为true,开发过程通常设为false,上线设为truespring.thymeleaf.cache = truespring.thymeleaf.encoding = UTF-8spring.thymeleaf.mode = HTML5#指定模板的存放路径,默认为classpath:/templates/spring.thymeleaf.prefix = classpath:/templates/#指定模板页面后缀spring.thymeleaf.suffix = .html
静态资源的访问,SpringBoot默认会查找resources目录下的public、resources、static文件夹。
- 编写html页面,web控制器进行跳转。页面示例:
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1,shrink- to-fit=no"><title>用户登录界面</title><link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet"><link th:href="@{/login/css/signin.css}" rel="stylesheet"></head> <body class="text-center"><!-- 用户登录form表单 --><form class="form-signin"><img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72"><h1 class="h3 mb-3 font-weight-normal">请登录</h1><input type="text" class="form-control" th:placeholder="用户名" required="" autofocus=""><input type="password" class="form-control" th:placeholder="密码" required=""><div class="checkbox mb-3"><label> <input type="checkbox" value="remember-me"> 记住我 </label></div><button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button><p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p></form></body></html>
- 通过“xmlns:th=”http://www.thymeleaf.org"”引入了Thymeleaf模板标签;
- 使用“th:href”和“th:src”分别引入了两个外联的样式文件和一个图片;
- 使用“th:text”引入了后台动态传递过来的当前年份currentYear
5.2 SpringBoot配置国际化页面
