SpringBoot学习笔记【part12】Web开发——Thymeleaf模板引擎

SpringBoot 学习笔记 Part12

1. thymeleaf简介

SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.

即 thymeleaf 是现代化、服务端的Java模板引擎。


2. 基本语法

  • 表达式

    表达式名语法作用
    变量取值${…}获取请求域、session域、对象等值
    选择变量*{…}获取上下文对象值
    消息#{…}获取国际化等值
    链接@{…}生成链接
    片段表达式~{…}jsp:include 作用,引入公共页面片段
    行内表达式[[…]]HTML 文本中嵌套表达式
  • 字面量

    文本值:‘one text’ , ‘another one’

    数字:0 , 34 , 3.0 , 12.3

    布尔值:true , false

    空值:null

    变量:one,two

  • 文本操作

    字符串拼接: +

    变量替换: |The name is ${name}|

  • 数字运算

    运算符: + , - , * , / , %

  • 布尔运算

    运算符: and , or

    一元运算: ! , not

  • 比较运算

    比较: > , < , >= , <= ( gt , lt , ge , le )

    等式: == , != ( eq , ne )

  • 条件运算

    If-then: (if) ?(then)

    If-then-else: (if) ? (then) :(else)

    Default: (value) ? :(defaultvalue)

  • 特殊操作

    无操作: _


3. 标签th:attr

th:attr 用来设置属性值。

  • 设置单个值:
<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>
  • 设置多个值:
<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
  • 以上两个的代替写法:
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">

所有h5兼容的标签写法可参考官方文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes


4. 迭代

foreach:

  • 迭代普通类型:
<tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
  • 迭代对象:
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

5. 条件运算

if:

<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>

switch:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

6. 属性优先级

所有Thymeleaf属性都有一个数字优先级,以建立他们在标签中的顺序执行。这个顺序是:

OrderFeatureAttributes
1Fragment inclusionth:include 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, etc.
7Text (tag body modification)th:text th:utext
8Fragment specificationth:fragment
9Fragment removalth:remove

7. thymeleaf的使用

首先,我们需要引入thymeleaf的starter场景启动器。

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

我们可以在 springboot 中找到 thymeleaf 的自动配置类,这说明springboot已经为我们做好了默认配置的工作。

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration { }

查看 springboot 的 thymeleaf 的自动配置类,在自动配置类里我们可以找到一些已经配好的重要组件,如spring模板引擎 SpringTemplateEngine、thymeleaf 的视图解析器 ThymeleafViewResolver 等。并且我们发现所有thymeleaf的配置值都在 ThymeleafProperties 类里,这个是存储配置信息的配置类,之前学习过。

public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";  //xxx.html

ThymeleafProperties 类中这两个重要属性表明了我们开发的页面路径和映射规则,因此我们不需要别的配置,直接进行开发就行了。

注:在html页面开发中为了更方便地使用thymeleaf标签属性,应在标签中引入thymeleaf的命名空间 xmlns:th=“http://www.thymeleaf.org”,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

8. 开发小案例

h5中编写如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1 th:text="${msg}">Hello H5 !</h1>
<h2>
  <a href="www.4399.com" th:href="${link}">去百度</a>
</h2>

</body>
</html>

Controller中编写如下:

@Controller
public class thymeleafController {

    @GetMapping("/thymeleaf")
    public String gotoThymeleaf(Model model){
        model.addAttribute("msg","Hello Thymelef !");
        model.addAttribute("link","http://www.baidu.com");
        return "success";
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Parker7

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

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

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

打赏作者

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

抵扣说明:

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

余额充值