与SpringBoot的整合步骤:
-
pom中增加配置
<!-- 引入 thymeleaf 模板依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
application.properties中增加如下配置
#资源文件配置 ############################################################ # # thymeleaf 静态资源配置 # ############################################################ #定义模板所在的目录:templates目录下面 spring.thymeleaf.prefix=classpath:/templates/ #定义模板的后缀名 spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # 关闭缓存, 即时刷新, 上线生产环境需要改为true spring.thymeleaf.cache=false
-
Controller中返回Model与templates路径
package com.yh.controller; import java.util.ArrayList; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.yh.entity.User; @Controller @RequestMapping("thymeleaf") public class ThymeleafController { @RequestMapping("finduser") public String finduser(ModelMap map) { User u = new User(); u.setName("heng"); u.setAge(21); u.setUrl("https://blog.youkuaiyun.com/qq_39313596"); u.setDesc("<a href='https://blog.youkuaiyun.com/qq_39313596'>博客地址</a>"); map.addAttribute("u",u); ...... return "/thymeleaf/index"; //对应的视图路径为:templates/thymeleaf/index.html } @PostMapping("saveUser") public String saveUser(User u) { System.out.println(u); return "redirect:../thymeleaf/finduser";//重定向到:templates/thymeleaf/finduser.html } }
-
Html中使用(常用标签)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <!-- <script th:src="@{/static/js/test.js}"></script> --> <!-- 引入js文件 需要在后端资源文件配置thymeleaf引入静态文件 --> <body> <!--输出文本--> <p th:text="${u.name}"></p> <!--java bean--> <div th:object="${u}"> <p th:text="*{name}"></p> <p th:text="*{age}"></p> <p th:text="*{url}"></p> <p th:text="*{desc}"></p> <p th:utext="*{desc}"></p> </div> <!--填充select from表单--> <form th:action="@{saveUser}" method="post" th:object="${u}" th:method="post"> <input type="text" th:field="*{name}"/> <input type="text" th:field="*{age}"/> <input type="text" th:field="*{url}"/> <input type="text" th:field="*{desc}"/> <input type="submit"/> </form> <!--select 选中--> <select> <option >选择框</option> <option th:selected="${u.name eq 'lee'}">lee</option> <!-- eq是等于的意思 --> <option th:selected="${u.name eq 'heng'}">heng</option> <option th:selected="${u.name eq 'LeeCX'}">LeeCX</option> </select> <table> <!--循环遍历--> <tr th:each="person:${list}"> <td th:text="${person.age}"></td> <!--三目运算--> <td th:text="${person.age gt 18} ? 你成熟了 : 你还年轻">18岁</td> <!--格式化日期--> <!-- <td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd hh:mm:ss')}"></td> --> </tr> </table> <br/> <br/> <!--条件判断--> <div th:switch="${u.name}"> <p th:case="'lee'">lee</p> <p th:case="A">普通管理员</p> <p th:case="heng">超级管理员</p> <p th:case="*">其他用户</p> </div> <br/> </body> </html>