赞
踩
Thymeleaf是一个现代的服务器端 Java 模板引擎,适用于 Web 和独立环境。
官方网址
Thymeleafhttps://www.thymeleaf.org/pom.xml文件Thymeleaf依赖项
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
在模板中加入解析
- <!DOCTYPE html>
- <html lang="zh_cn" xmlns:th="http://www.thymeleaf.org/"
- xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
后面这个是要用到spring security的相关数据时要用到的命名空间,暂且不提。
application.properties文件中关于thymeleaf的配置项
- spring.thymeleaf.model=HTML5
- spring.thymeleaf.encoding=UTF-8
- spring.thymeleaf.content-type=text/html
- spring.thymeleaf.cache=false
常用th标签
- <p th:text="${name}"></p>
- 显示文本
th:object
- <p th:object="${object}"></p>
- 显示对象
th:action
- <form th:action="@{/person/}+${person.id}" method="post"></form>
- 用于指定表单提交地址
th:value
th:field
URL写法
th:href="@{http://www.baidu.com}"
th:href="@{/}"
th:href="@{css/bootstrap.min.css}"
条件求值
th:if th:unless
th:switch
th:case
运算符
+ - * /
<p th:text="1+2"></p>
遍历
th:each
- <div th:each="item:${items}">
- <span th:text="${item.name}"></span>
- </div>
处理公共代码
th:fragment th:include th:replace
新建一个简单的model类 User
- public class User {
- private long id;
- private String name;
- private int age;
-
- public long getId() {
- return id;
- }
-
- public void setId(long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
- }

创建控制器UserController
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.servlet.ModelAndView;
-
- import java.util.ArrayList;
- import java.util.List;
-
- @Controller
- public class UserController {
- @GetMapping("/user")
- public ModelAndView hello(){
- List<User> list = new ArrayList<User>();
- User user = new User();
- user.setName("张三");
- user.setAge(17);
- list.add(user);
- User lisi = new User();
- lisi.setName("李四");
- lisi.setAge(19);
- list.add(lisi);
- User wangwu = new User();
- wangwu.setName("王五");
- wangwu.setAge(19);
- list.add(wangwu);
- ModelAndView model = new ModelAndView("user");
- model.addObject("users",list);
- return model;
- }
- }

这里的model的名字就是html文件的名字,一开始没搞明白。
创建view 就是html user.html
- <!DOCTYPE html>
- <html lang="zh_cn" xmlns:th="http://www.thymeleaf.ort">
- <head>
- <meta charset="UTF-8">
- <title>this is user test page</title>
- </head>
- <body>
- <table border="1">
- <tr>
- <th>姓名</th>
- <th>年龄</th>
- </tr>
- <tr th:each="user : ${users}">
- <td th:text="${user.name}"></td>
- <td th:text="${user.age}"></td>
- </tr>
- </table>
- </body>
- </html>

运行显示。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。