thymeleaf特点是语法更简单,功能更强大。
1 引入thymeleaf (版本不同,<version>2.3.3.RELEASE</version>可加或不必加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
加入版本修改
通过以下方式切换thymeleaf版本
<proerties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序,thymeleaf3的主程序,2版本以上支持-->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
此处要注意版本的冲突。
此处报would dispatch back to the current handler URL,后把版本切换给注释掉以后,执行成功。
文件HelloController.java
package com.yjg.springbootweb.springbootwebdisplaycrud.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World!"; } @RequestMapping("/success") public String success(){ //classpath:/templates/ok.html return "ok"; } }
文件ok.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>成功!</h1> </body> </html>
总结:只要把html放到//classpath:/templates/下,thymeleaf会自动渲染。
2 使用
1 在html里导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2 使用thymeleaf的语法
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 将div里面的文本内容设置为指定值--> <div th:text="${hello}">这是欢迎信息!!!</div> <h1>成功!</h1> </body> </html>
语法规则:
1 th:text 改变当前元素里面的文本内容。
th: 任意html属性,来替换原生属性的值。
2 表达式
OK文件 <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 将div里面的文本内容设置为指定值--> <div th:text="${hello}">这是欢迎信息!!!</div> <div th:utext="${hello}"></div> <hr> <h4 th:text="${user}" th:each="user:${users}"></h4> <hr> <h4> <span th:each="user:${users}">[[${user}]]</span> </h4> <h1>成功!</h1> </body> </html>
controllere文件
import java.util.Arrays; import java.util.Map; @Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World!"; } @RequestMapping("/success") public String success(Map<String,Object> map){ map.put("hello","<h1>您好!</h1>"); map.put("users", Arrays.asList("zhangsan","lisi","wangwu","zhaoliu")); //classpath:/templates/ok.html return "ok"; } }