Spring Boot Thymeleaf

本文详细介绍如何在Spring Boot项目中快速配置并使用Thymeleaf模板引擎,包括Maven依赖导入、HTML模板创建、Controller编写及Thymeleaf标签语法解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、简单配置

1.1、导入 maven 依赖

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

1.2、新建 html 模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>test</h1>
<div th:text="${msg}"></div>
</body>
</html>

必须在 html 中配置约束 xmlns:th="http://www.thymeleaf.org" 才可以使用 thymeleaf

1.3、创建 controller

@RequestMapping("/test")
public String test1(Model model){
    model.addAttribute("msg", "this is msg");
    return "test";
}

1.4、测试

在这里插入图片描述

2、相关标签

2.1、取值方式

  • Simple expressions:
    • Variable Expressions: ${…}
    • Selection Variable Expressions: *{…}
    • Message Expressions: #{…}
    • Link URL Expressions: @{…}
    • Fragment Expressions: ~{…}
  • Literals
    • Text literals: ‘one text’ , ‘Another one!’ ,…
    • Number literals: 0 , 34 , 3.0 , 12.3 ,…
    • Boolean literals: true , false
    • Null literal: null
    • Literal tokens: one , sometext , main ,…
  • Text operations:
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations:
    • Binary operators: + , - , * , / , %
    • Minus sign (unary operator): -
  • Boolean operations:
    • Binary operators: and , or
    • Boolean negation (unary operator): ! , not
  • Comparisons and equality:
    • Comparators: > , < , >= , <= ( gt , lt , ge , le )
    • Equality operators: == , != ( eq , ne )
  • Conditional operators:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • Special tokens:
    • No-Operation: _

2.2、标签

OrderFeatureAttributes
1Fragment inclusionth:insert
th:replace
2Fragment iterationth:each
3Conditional evaluationth:if
th:unless
th:switch
th:case
4Local variable definitionth:object
th:with
5General attribute modificationth:attr
th:attrprepend
th:attrappend
6Specific attribute modificationth:value
th:href
th:src
7Text (tag body modification)th:text
th:utext
8Fragment specificationth:fragment
9Fragment removalth:remove
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌尘吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值