Thymeleaf入门

前言

入门级demo,仅供小伙伴入门,不涉及过多的教程(多了我也不会),入门后需要其他的知识点再慢慢去百度吧(摊手),本文对CRUD的小伙伴比较友好

四步入门Thymeleaf

步骤1:修改pom.xml文件,添加thymeleaf依赖(注:还需要添加properties)

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

<properties>
    <springboot-thymeleaf.version>3.0.9.RELEASE</springboot-thymeleaf.version>
    <!--布局功能的支持查询 thymeleaf3主程序  layout2以上版本-->
    <!--thymeleaf2 layout1-->
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>

步骤2:添加一个配置类ThymeLeafProperties

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.MimeType;
import java.nio.charset.Charset;

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeLeafProperties {

    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
}

步骤3:创建一个Controller,用于浏览器访问

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Map;

@Controller
public class Hello {

    @RequestMapping("/success")
    public String success(Map map) {
        map.put("hello", "<h1>你好</h1>");
        map.put("users", Arrays.asList("张三", "lisi", "王五"));
        return "success";
    }
}

注:这里不采用@RestController注解,因为它默认会把所有返回结果的格式转为json

步骤4:在resources资源路径下的templates中添加我们的html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
    <h1>成功</h1>
    <div>
        <!--转义-->
        <p th:text="${hello}"></p>
        <!--不转义-->
        <p th:utext="${hello}"></p>
    </div>
    <br>
    <h2 th:each="user:${users}" th:text="${user}"></h2>
    <hr/>
    <h2>
        <span th:each="user:${users}">[[${user}]]</span>
    </h2>
</body>
</html>

在这里插入图片描述
备注1:thymeleaf的页面都需要放在resources/thymeleaf路径下
备注2:需要引入命名空间 xmlns:th="http://www.thymeleaf.org"
备注3:thymeleaf的更多用法,网上很多地方都有了,这里就不搬过来劝退小伙伴了

最后就是效果了,访问http://localhost:8080/success,到这一步,入门就算完了
在这里插入图片描述

参考文章

web开发 模板引擎

结语

关于thymeleaf,我也是在自己的单体项目中使用过,不过现在很多项目都是前后端分离的,留给thymeleaf页面模板引擎的发挥空间好像没那么多了,不知道自己的理解是否有误,欢迎小伙伴留言勘误(免得我妖言惑众),by the way,侵权必删。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值