Spring Boot(四):Spring Boot 集成 Thymeleaf

本文介绍了如何在Spring Boot中集成Thymeleaf模板引擎,通过添加Maven依赖、改造HTML代码,展示了th:href、th:action、th:object和th:field的使用方法。Thymeleaf允许在浏览器中直接预览静态模板,并在有数据时动态渲染。

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

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用,这是由于它支持 html 原型,然后在html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释html 时会忽略未定义的标签属性,所以thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。—-摘自百度君。

要写出简洁优雅的前台代码,Spring Boot 君推荐使用Thymeleaf替代jsp。接下来咱们就看看如何利用Thymeleaf模板引擎写出优雅的html代码。

1.1 添加Maven依赖

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

可以查看依赖关系,发现spring-boot-starter-thymeleaf下面已经包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依赖去掉.

1.2 改造html代码

接下来我们以login登录界面来谈谈Thymeleaf模板引擎的使用方法
还是以上一篇博客《Spring boot(三):@RequestMapping之Form表单参数传递及POJO绑定实例讲解》的工程项目为基础,改造一下我们的登录界面

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>

    <title>Login</title>

    <link rel="stylesheet" href="/SpringBootBase/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="/SpringBootBase/css/customer/login.css"/>
</head>

<body>
    <div class="container">
        <form class="form-signin" action="./login" method="post">
            <h2 class="form-signin-heading">请 登 录</h2>
            <input type="text" class="form-control" placeholder="账号" name="username"/>
            <input type="password" class="form-control" placeholder="密码" name="password"/> 
            <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
        </form>
    </div>
</body>
</html>

1.2.1 xmlns:th命名空间

使用Thymeleaf引擎需要在html标签添加Thymeleaf模板引擎的命名空间:xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值