Spring boot 入门学习3. 使用Thymeleaf模板引擎

版权声明:(谢厂节的博客)博主文章绝大部分非原创,转载望留链接。 https://blog.csdn.net/xundh/article/details/82385913

Thymeleaf 是一个面向Java的 XML/XHTML/HTML5页面模板,具有丰富的标签语言和函数。 使用SpringBoot进行页面设计时,一般都会选Thymeleaf模板。

依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

项目结构

这里写图片描述

代码

UserController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@RequestMapping("user")
@Controller
public class UserController {


    @RequestMapping("/list")
    public String list() {
        return "/user/list";

    }
}

DemoApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

模板页
list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>list.html</title>
</head>
<body>
  <h2>用户列表</h2>
  <div>
     <ul>
         <li th:each="user:${users}">
             <p>ID:<span th:text="${user.id}"></span></p>
             <p>名字:<span th:text="${user.username}"></span></p>
             <p>年龄:<span th:text="${user.age}"></span></p>
             <p>地址:<span th:text="${user.address}"></span></p>
         </li>
     </ul>
   </div>
</body>
</html>

这里暂时没有连接具体数据。

常用表达式

  • ${…} 变量表达式
  • *{…} 选择表达式
  • #{…} 消息文字表达式
  • @{…} 链接url表达式
  • #maps 工具对象表达式

常用标签

  • th:action 定义后台控制器路径
  • th:each 循环语句
  • th:field 表单字段绑定
  • th:href 定义超链接
  • th:id div 标签中的ID声明,类似HTML标签中的ID属性
  • th:if 条件判断语句
  • th:include 布局标签,替换内容到引入文件
  • th:fragment 布局标签,定义一个代码片段,方便其它地方引用
  • th:object 替换对象
  • th:src 图片类地址引入
  • th:text 显示文本
  • th:value 属性赋值
  • -

常用函数

  • #dates 日期函数
  • #lists 列表函数
  • arrays 数组函数
  • strings 字符串函数
  • numbers 数字函数
  • calendars 日历函数
  • #objects 对象函数
  • #bools 逻辑

猜你喜欢

转载自blog.csdn.net/xundh/article/details/82385913