首页 > Java > java教程 > 正文

SpringBoot中如何使用Thymeleaf模板

WBOY
发布: 2023-05-17 19:19:51
转载
1451人浏览过

一.什么是Thymeleaf

官网原话:thymeleaf是适用于web和独立环境的现代服务器端java模板引擎,能够处理html,xml,javascript,css甚至纯文本。thymeleaf旨在提供一种优美而易于维护的模板创建方式。它以自然模板为蓝本,以不影响模板作为设计原型的方式,将逻辑注入模板文件。这样可以改善设计沟通,并缩小设计团队与开发团队之间的差距。thymeleaf是一种用于web应用程序开发的html5模板引擎。thymeleaf提供了一个用于整合spring mvc的可选模块,在应用开发中,你可以使用thymeleaf来完全代替jsp或其他模板引擎,如velocity、freemarker等。thymeleaf的主要目的是为了提供一种能够生成格式良好的模板,并能被浏览器正确显示的创建方式。thymeleaf模板引擎,替代jsp。

二.SpringBoot中使用Thymeleaf模板

1.pom.xml中添加thymeleaf依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
登录后复制

2.关闭thymeleaf缓存

在application.yml中的spring:下添加如下代码(能让改动的页面及时生效,实现类似热部署效果):

#能让改动的页面及时生效,实现类似热部署效果
thymeleaf:
    cache: false
登录后复制

注意缩进,添加后缩进如下:

SpringBoot中如何使用Thymeleaf模板

3.创建thymeleaf模板页面

创建一个普通的html文件hello.html,如下:

AiPPT模板广场
AiPPT模板广场

AiPPT模板广场-PPT模板-word文档模板-excel表格模板

AiPPT模板广场 147
查看详情 AiPPT模板广场
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>
</html>
登录后复制

在html的标签上加入名称空间xmlns:th="http://www.thymeleaf.org"表示该页面是一个thymeleaf模板页面。 即把上述代码中<html lang="en">换成<html lang="en" xmlns:th="http://www.thymeleaf.org"> 这样就可以在页面中的标签内使用th属性取出model中的值,类似于EL表达式。 具体用法代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="'欢迎来到中国,我叫'+${name}+',今年'+${age}+'岁。'"></p>
    <p>欢迎来到中国,我叫<span th:text="${name}"></span>,今年<span th:text="${age}"></span>岁。</p>
</body>
</html>
登录后复制

4.创建一个类(用于与上述html页面交互)

ackage com.ysw.springboot01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/thy")
public class ThymeleafController {
    @RequestMapping("/hello")
    public String hello0(Model model){
        //向model中存入数据
        model.addAttribute("name","李白");
        model.addAttribute("age","18");
        //跳转到hello.html模版引擎
        return "hello";
    }
}
登录后复制

5.访问服务路径

效果如下:

SpringBoot中如何使用Thymeleaf模板

以上就是SpringBoot中如何使用Thymeleaf模板的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:亿速云网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号