Thymeleaf的使用

简介: 最近听说thymeleaf好像也挺流行的,还说是spring官方推荐使用,那thymeleaf究竟是什么呢?spring为什么推荐用它呢?怎么用呢?本文将为你揭秘!

一、thymeleaf简介:


thymeleaf是一种Java模板引擎,那何为模板引擎呢?模板引擎就是为了使用户页面和业务数据相互分离而出现的,将从后台返回的数据生成特定的格式的文档,这里说的特定格式一般都指HTML文档。它能够处理html、xml、js、css甚至纯文本,类似于freemarker。它的优点是语法优雅易懂、原型即页面、遵从web标准。原型即页面是它的特色,所谓原型即页面,就是你写的html,静态的去访问是什么样,动态的去访问还是这样,只不过动态的时候会把数据填充进去。


二、thymeleaf标准方言:


1、变量表达式:${...}


例如前端接收一个user,想取出user的name属性,就可以用变量表达式:

<span th:text="${user.name}">


2、消息表达式:#{...}


也称为文本外部化、国际化或i18n.

<p th:text=" #{header.address.city}" >...</p>


3、选择表达式:*{...}


与变量表达式的区别:选择表达式是在当前选择的对象上执行而不是整个上下文。

<form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">
   <input type="hidden" name="id" th:value="*{id}">
</form>


这里id就用了选择表达式,在此处*{id}与${userModel.user.id}效果一样。


4、链接表达式:@{...}


url可以是相对的,也可以是绝对的。

<a th:href="@{.../users/list}">...</a>
<a th:href="@{http://www.baidu.com}">...</a>


5、分段表达式:th:insert 、th:replace 、th:include


就相当插入。这三个的区别:


现有一个片段如下:

<footer th:fragment="copy">
   <h1> Hello Thymeleaf </h1>
</footer>


#号分别代表insert、replace、include进行操作:

<div th:#="footer :: copy"></div>


th:insert 的结果:

<div>
  <footer th:fragment="copy">
     <h1> Hello Thymeleaf </h1>
  </footer>
</div>


把footer标签插入到了div标签中。


th:replace的结果:

<footer th:fragment="copy">
   <h1> Hello Thymeleaf </h1>
</footer>


把div标签换成了footer标签。


th:include的结果:

<div>
   <h1> Hello Thymeleaf </h1>
<div>


把div标签里面的内容换成了footer标签里面的内容。3.X版本后不再推荐使用。


6、字面量:


字面量可以是文本、数字、布尔和null等类型。


7、算术操作:+、-、*、/、%


例如:

<div th:with="isEven=(${user.age} % 2 == 0)">


8、其他运算符:


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


等价:==、!= (eq、ne)


三目运算符:

<tr th:class="${row.even} ? 'even' : 'odd' "></tr>


9、迭代器:th:each


相当于Java的foreach.

<tr th:each="user : ${userList}">
         <td th:text="${user.id}"></td>
         <td th:text="${user.email}"></td>
</tr>


这样就是遍历userList集合。


迭代器的状态变量有:


index、count、size、current、even/odd、first、last


10、条件语句:th:if、th:unless、switch

<div th:switch="${user.role}">
   <p th:case=" 'admin' ">User is admin</p>
   <p th:case=" 'guest' ">User is guest</p>
</div>


11、模板布局:th:fragment


比如定义一个公用的页头:

<div th:fragment="header">
   <h1>Thymeleaf in action</h1>
   <a href="/users" >首页</a>
</div>


在其他页面直接这样引用就行:

<div th:replace="~{fragments/header :: header}"></div>


12、表达式基本对象:


表达式基本对象有:param、session、application、request、servletContext。


三、thymeleaf与springboot集成案例:


本案例使用gradle构建,未涉及数据库,数据保存在ConcurrentMap中。未曾了解gradle的老铁可以参考一下gradle的使用。点我下载本案例源码。


项目结构如下:


image.png


1、添加依赖:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    //thymeleaf的依赖
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
}


2、application.properties:

#thymeleaf相关配置
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5


3、entity层:

public class User {
    private Long id;
    private String name;
    private String email;
}


4、dao层:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;
import com.zhu.test.dao.UserDao;
import com.zhu.test.entity.User;
/**
 * user dao层实现
 * @author zhu
 *
 */
@Repository
public class UserDaoImpl implements UserDao {
    //用来计数的
    private static AtomicLong counter = new AtomicLong();
    // 用来保存user的map
    private final ConcurrentMap<Long, User> userMap = new ConcurrentHashMap<>();
    @Override
    public User saveOrUpdateUser(User user) {
        Long id = user.getId();
        if(id == null) {//save
            id = counter.incrementAndGet();
            user.setId(id);
        }
        this.userMap.put(id, user);
        return user;
    }
    @Override
    public void deleteUser(Long id) {
        this.userMap.remove(id);
    }
    @Override
    public User getUserById(Long id) {
        return this.userMap.get(id);
    }
    @Override
    public List<User> listUsers() {
        return new ArrayList<User>(this.userMap.values());
    }
}


将user保存在ConcurrentMap中,crud操作其实都是对这个map进行操作。


5、controller层:

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserDao userDao;
    /**
     * 查询所有用户
     * 
     * @param model
     * @return
     */
    @GetMapping
    public ModelAndView list(Model model) {
        model.addAttribute("userList", userDao.listUsers());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("user/list", "userModel", model);
    }
    /**
     * 根据id查询用户
     * 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        User user = userDao.getUserById(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "查看用户");
        return new ModelAndView("user/view", "userModel", model);
    }
    /**
     * 获取创建表单页面
     * 
     * @param model
     * @return
     */
    @GetMapping("/form")
    public ModelAndView createForm(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("title", "创建用户");
        return new ModelAndView("user/form", "userModel", model);
    }
    /**
     * 保存或更新用户
     * 
     * @param user
     * @return
     */
    @PostMapping
    public ModelAndView saveOrUpdateUser(User user) {
        user = userDao.saveOrUpdateUser(user);
        return new ModelAndView("redirect:/users");
    }
    /**
     * 删除用户
     * 
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id) {
        userDao.deleteUser(id);
        return new ModelAndView("redirect:/users");// 重定向到list页面
    }
    /**
     * 获取修改用户的界面
     * 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/modify/{id}")
    public ModelAndView modify(@PathVariable("id") Long id, Model model) {
        User user = userDao.getUserById(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return new ModelAndView("user/form", "userModel", model);
    }
}


6、前端页面:


注意:要使用thymeleaf,需要在html标签中加上

xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"


如下页面:


页头:header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>thymeleaf in action</title>
</head>
<body>
<div th:fragment="header">
   <h1>Thymeleaf in action</h1>
   <a href="/users" >首页</a>
</div>
</body>
</html>


页脚:footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>thymeleaf in action</title>
</head>
<body>
<div th:fragment="footer">
   <a href="#" >邮箱</a>
</div>
</body>
</html>


form.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>thymeleaf in action</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}"></div>
<h3 th:text="${userModel.title}">test</h3>
<form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">
   <input type="hidden" name="id" th:value="*{id}">
   名称:<br>
   <input type="text" name="name" th:value="*{name}"><br>
   邮箱:<br>
   <input type="text" name="email"th:value="*{email}">
   <input type="submit" value="提交">
</form>
<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>


list.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>thymeleaf in action</title>
</head>
<body>
<!-- 引用头部信息 -->
<!-- 在fragments下的header文件下有名为header的片段 -->
<div th:replace="~{fragments/header :: header}"></div>
<h3 th:text="${userModel.title}"></h3>
<div>
   <a href="/users/form.html" th:href="@{/users/form}">创建用户</a>
</div>
<table border="1">
   <thead>
      <tr>
         <td>ID</td>
         <td>Email</td>
         <td>Name</td>
      </tr>
   </thead>
   <tbody>
     <tr th:if="${userModel.userList.size()} eq 0">
         <td colspan="3">没有用户信息</td>
     </tr>
     <tr th:each="user : ${userModel.userList}">
         <td th:text="${user.id}"></td>
         <td th:text="${user.email}"></td>
         <td ><a th:href="@{'/users/'+${user.id}}" th:text="${user.name}"></a></td>
     </tr>
   </tbody>
</table>
<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>


view.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>thymeleaf in action</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}"></div>
<h3 th:text="${userModel.title}">test</h3>
<div>
   <p><strong>ID:</strong><span th:text="${userModel.user.id}"></span></p>
   <p><strong>Name:</strong><span th:text="${userModel.user.name}"></span></p>
   <p><strong>Email:</strong><span th:text="${userModel.user.email}"></span></p>
</div>
<div>
   <a th:href="@{'/users/delete/'+${userModel.user.id}}">删除</a>
   <a th:href="@{'/users/modify/'+${userModel.user.id}}">修改</a>
</div>
<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>


以上页面就涉及到了thymeleaf的常用标签,通过这几个页面,理解thymeleaf的用法。


7、测试效果:

image.png


点击“创建用户”:


image.png

点击“提交”后:


image.png

点击name栏可以进入view页面:


image.png


这个页面还可以进行删除和修改,这里不再截图。


总结:


thymeleaf标签看起来很多,其实常用的也不多,且很好理解。主要别忘了在html标签中需要加上xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"。


如果eclipse写thymeleaf标签时没有提示,安装一下thymeleaf插件重启eclipse即可,点击help --> install new software,地址为:http://www.thymeleaf.org/eclipse-plugin-update-site/.


image.png





相关文章
|
监控 安全 JavaScript
【web渗透思路】框架敏感信息泄露(特点、目录、配置)
【web渗透思路】框架敏感信息泄露(特点、目录、配置)
1532 0
【web渗透思路】框架敏感信息泄露(特点、目录、配置)
|
3月前
|
存储 人工智能 Java
1TB库克隆从小时级到秒级,开发环境不再靠手搓
从AI编程时代开发环境不够用的痛点出发,讲清数据库秒级克隆的底层原理(copy-on-write与写重定向两条路线、引用计数与垃圾回收的工程差异)、三种实现层次(逻辑复制/存储快照/数据库原生COW),结合Neon、TDSQL-C及金仓KES的布局,给出三种落地模式(按开发、按PR、给Agent)、配额回收权限三个管理要点,以及一次配额被打爆的真实复盘与避坑清单。
|
4月前
|
人工智能 Shell API
花了一整夜实测DeepSeek Harness:它比Claude Code强在哪?
DeepSeek Harness v0.1开源引爆社区:非Claude Code竞品,而是开放Agent底座。它将模型(大脑)与Harness(手脚+神经)解耦,支持插件化替换全部组件,可编排Claude Code/Codex等子Agent,具备Headless批量任务、高可观测性与低成本优势,适合需深度定制与自动化落地的开发者团队。
|
5月前
|
编解码 缓存 人工智能
从 ffmpeg.wasm 到 WebCodecs:浏览器视频编辑器导出架构的演进与实践
本文介绍了一种混合架构的浏览器视频编辑器导出方案:以Canvas+WebCodecs逐帧合成与编码、OfflineAudioContext混音为核心,ffmpeg.wasm仅负责音频提取、格式标准化及MP4转码等专项任务,兼顾预览一致性、性能与容错性。(239字)
从 ffmpeg.wasm 到 WebCodecs:浏览器视频编辑器导出架构的演进与实践
|
5月前
|
人工智能 弹性计算 自然语言处理
零代码建站 + 全链路运营!阿里云万小智 AI 员工,10 分钟搞定品牌官网从设计到上线
万小智是阿里云推出的AI建站平台,基于通义大模型,集成AI建站、创意配图、智能客服、内容创作四大能力,10分钟极速上线品牌官网;预置多行业模板,支持对话式修改;原生集成阿里云安全与算力,备案发布一站式完成,让小微企业轻松拥有专业线上阵地。
|
机器学习/深度学习 人工智能 Linux
anaconda conda 切换为国内源 、windows 和 Linux配置方法、 添加清华源——【一文读懂】
请问为什么我使用 Conda 搭建一个深度学习环境半个多小时都没成,而你10分钟就随手搭建一个环境; 讲道理,这就像搬砖,搬的久了,还不能允许我一天多拉几车吗
7521 0
anaconda conda 切换为国内源 、windows 和 Linux配置方法、 添加清华源——【一文读懂】
|
消息中间件 监控 数据可视化
实时看板数据分析的力量:推动高效决策的17个关键维度
实时看板数据分析通过可视化工具将企业运营数据实时整合展示,助力快速决策。它结合数据收集、处理与交互分析,广泛应用于制造、零售、金融等领域,提升响应速度与协作效率。技术上依赖流数据处理与可视化工具,如Power BI、Tableau等,同时关注数据安全与用户体验优化。
862 1
|
11月前
|
人工智能 自然语言处理 网络协议
从 1800ms 到 320ms:企业级场景下 Gemini API 跨境延迟的工程解法
本文剖析Gemini API在国内落地时的跨境高延迟问题(首包1.5–2秒、流式不稳),指出其本质是TCP握手开销、队头阻塞与链路抖动等工程瓶颈。提出HTTP/3升级、稳定中间入口、流式传输优化三类方案,实测将首包延迟从1800ms降至320ms,并强调系统可控性比极限速度更重要。
|
前端开发 JavaScript 开发者
前端 CSS 优化:提升页面美学与性能
前端CSS优化旨在提升页面美学与性能。通过简化选择器(如避免复杂后代选择器、减少通用选择器使用)、合并样式表、合理组织媒体查询,可减少浏览器计算成本和HTTP请求。利用硬件加速和优化动画帧率,确保动画流畅。定期清理冗余代码并使用缩写属性,进一步精简代码。这些策略不仅加快页面加载和渲染速度,还提升了视觉效果,为用户带来更优质的浏览体验。
|
12月前
|
存储 SQL 数据库
C 语言持久层开发:从文件操作到轻量级数据库的实践
C语言无内置数据库支持,持久化需依赖文件操作或轻量级库。本文详解文本/二进制文件与SQLite的实现原理及选型:文件适配资源受限场景,SQLite支持复杂查询,二者结合可构建高效、可靠的嵌入式持久化方案。