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