SpringBoot常用模板引擎有 freemarker 和 thymeleaf,更推荐使用 thymeleaf。整合 thymeleaf 模板引擎很简单,只有两个步骤:
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>添加 application.yml 配置:
spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 cache: false #关闭缓存,生产环境建议设为true servlet: content-type: text/html在resources/templates下创建一个index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${name}">你好</h1> </body> </html>代码中h1标签中的th:text="${name}" 是thymeleaf模板引擎的语法,如果控制器中有给name的值,那么你好 就会被替换为name的值
创建一个Controller,使用@Controller 注解,注意不能使用@RestController ,因为 @RestController 注解会将结果转化为JSON,而我们需要使用模板引擎。
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("/index") public String index(ModelMap map){ //传递name值给模板引擎 map.addAttribute("name","SpringBoot"); //return模板名称,不用写后缀 return "index"; } }就这么简单。
上面简单介绍了th:text ,现在再来介绍一些常用的模板标签
thymeleaf 基本都是以th开头,例如:
<input type="text" th:id="${user.username}" th:name="${user.username}" th:value="${user.username}">控制器:
@GetMapping("/index") public String index(ModelMap map){ User user = new User(); user.setUsername("springboot"); map.addAttribute("user",user); return "index"; }最后渲染结果:
对象中取值还有另外一种写法:
<div th:object="${user}"> <input type="text" th:value="*{username}"> </div>在文章最开头有一个<h1 th:text="${name}">你好</h1> 例子,text 会将文本内容原原本本显示,哪怕内容是一段html,也会被原原本本显示。
而utext 就会转换为html,例如:
@GetMapping("/index") public String index(ModelMap map){ map.addAttribute("name","<strong>SpringBoot</strong>"); return "index"; } <h1 th:text="${name}"></h1> <h1 th:utext="${name}"></h1>效果:
模板中引用地址的格式是:@{地址} ,例如:
<a th:href="@{http://www.baidu.com}"></a> <a th:href="@{/hello(id=${user.userId})}"></a> <a th:href="@{/hello/id/{userId}(userId=${user.userId})}"></a>效果:
先配置application.yml:
spring: mvc: static-path-pattern: /static/**静态资源放在resources/static目录下
引用:
<script th:src="@{/static/index.js}"></script>在表单中我们可以使用th:field,如:
<form action="" th:object="${user}"> <input type="text" th:field="*{username}"> </form>用了th:field,模板引擎会自动帮我们写好id,name,value属性,十分方便:
if判断:
<div th:if="${user.userId} == 10">10</div> <div th:if="${user.userId} gt 10">>10</div>比较符号有:
== 或 eq :等于gt:大于lt:小于ge:大等于le:小等于selected判断:
<select name="" id=""> <option value="">all</option> <option value=""th:selected="${user.username eq 'tom'}" >tom</option> <option value=""th:selected="${user.username eq 'jack'}" >jack</option> </select>switch判断:
<div th:switch="${user.username}"> <div th:case="'jack'">jack</div> <div th:case="'tom'">tom</div> <div th:case="*">其他</div> </div>