虽然如今慢慢在流行先后端分离开发,可是据松哥所了解到的,仍是有一些公司在作先后端不分的开发,而在先后端不分的开发中,咱们就会须要后端页面模板(实际上,即便先后端分离,也会在一些场景下须要使用页面模板,例如邮件发送模板)。javascript
早期的 Spring Boot 中还支持使用 Velocity 做为页面模板,如今的 Spring Boot 中已经不支持 Velocity 了,页面模板主要支持 Thymeleaf 和 Freemarker ,固然,做为 Java 最最基本的页面模板 Jsp ,Spring Boot 也是支持的,只是使用比较麻烦。html
松哥打算用三篇文章分别向你们介绍一下这三种页面模板技术。前端
今天咱们主要来看看 Thymeleaf 在 Spring Boot 中的整合!java
Thymeleaf 是新一代 Java 模板引擎,它相似于 Velocity、FreeMarker 等传统 Java 模板引擎,可是与传统 Java 模板引擎不一样的是,Thymeleaf 支持 HTML 原型。git
它既可让前端工程师在浏览器中直接打开查看样式,也可让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,所以在 SpringBoot 中使用 Thymeleaf 很是方便。github
事实上, Thymeleaf 除了展现基本的 HTML ,进行页面渲染以外,也能够做为一个 HTML 片断进行渲染,例如咱们在作邮件发送时,可使用 Thymeleaf 做为邮件发送模板。web
另外,因为 Thymeleaf 模板后缀为 .html
,能够直接被浏览器打开,所以,预览时很是方便。spring
Spring Boot 中整合 Thymeleaf 很是容易,只须要建立项目时添加 Thymeleaf 便可:后端
建立完成后,pom.xml 依赖以下:浏览器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
复制代码
固然,Thymeleaf 不只仅能在 Spring Boot 中使用,也可使用在其余地方,只不过 Spring Boot 针对 Thymeleaf 提供了一整套的自动化配置方案,这一套配置类的属性在 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
中,部分源码以下:
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = DEFAULT_PREFIX;
private String suffix = DEFAULT_SUFFIX;
private String mode = "HTML";
private Charset encoding = DEFAULT_ENCODING;
private boolean cache = true;
//...
}
复制代码
@ConfigurationProperties
注解,将 application.properties
前缀为 spring.thymeleaf
的配置和这个类中的属性绑定。static
变量定义了默认的编码格式、视图解析器的前缀、后缀等。Thymeleaf
模板的默认位置在 resources/templates
目录下,默认的后缀是 html
。application.properties
中以 spring.thymeleaf
开始相关的配置。而咱们刚刚提到的,Spring Boot 为 Thymeleaf 提供的自动化配置类,则是 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
,部分源码以下:
@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}
复制代码
能够看到,在这个自动化配置类中,首先导入 ThymeleafProperties
,而后 @ConditionalOnClass
注解表示当当前系统中存在 TemplateMode
和 SpringTemplateEngine
类时,当前的自动化配置类才会生效,即只要项目中引入了 Thymeleaf
相关的依赖,这个配置就会生效。
这些默认的配置咱们几乎不须要作任何更改就能够直接使用了。若是开发者有特殊需求,则能够在 application.properties 中配置以 spring.thymeleaf 开头的属性便可。
接下来咱们就能够建立 Controller 了,实际上引入 Thymeleaf 依赖以后,咱们能够不作任何配置。新建的 IndexController 以下:
@Controller
public class IndexController {
@GetMapping("/index")
public String index(Model model) {
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User u = new User();
u.setId((long) i);
u.setName("javaboy:" + i);
u.setAddress("深圳:" + i);
users.add(u);
}
model.addAttribute("users", users);
return "index";
}
}
public class User {
private Long id;
private String name;
private String address;
//省略 getter/setter
}
复制代码
在 IndexController
中返回逻辑视图名+数据,逻辑视图名为 index
,意思咱们须要在 resources/templates
目录下提供一个名为 index.html
的 Thymeleaf
模板文件。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>编号</td>
<td>用户名</td>
<td>地址</td>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.address}"></td>
</tr>
</table>
</body>
</html>
复制代码
在 Thymeleaf
中,经过 th:each
指令来遍历一个集合,数据的展现经过 th:text
指令来实现,
注意 index.html
最上面要引入 thymeleaf
名称空间。
配置完成后,就能够启动项目了,访问 /index 接口,就能看到集合中的数据了:
另外,Thymeleaf
支持在 js
中直接获取 Model
中的变量。例如,在 IndexController
中有一个变量 username
:
@Controller
public class IndexController {
@GetMapping("/index")
public String index(Model model) {
model.addAttribute("username", "李四");
return "index";
}
}
复制代码
在页面模板中,能够直接在 js 中获取到这个变量:
<script th:inline="javascript">
var username = [[${username}]];
console.log(username)
</script>
复制代码
这个功能算是 Thymeleaf 的特点之一吧。
前面咱们说的是返回一个 Thymeleaf 模板,咱们也能够手动渲染 Thymeleaf 模板,这个通常在邮件发送时候有用,例如我在 resources/templates 目录下新建一个邮件模板,以下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息以下:</p>
<table border="1">
<tr>
<td>职位</td>
<td th:text="${position}"></td>
</tr>
<tr>
<td>薪水</td>
<td th:text="${salary}"></td>
</tr>
</table>
<img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">
</body>
</html>
复制代码
这一个 HTML 模板中,有几个变量,咱们要将这个 HTML 模板渲染成一个 String 字符串,再把这个字符串经过邮件发送出去,那么如何手动渲染呢?
@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
Context context = new Context();
context.setVariable("username", "javaboy");
context.setVariable("position", "Java工程师");
context.setVariable("salary", 99999);
String mail = templateEngine.process("mail", context);
//省略邮件发送
}
复制代码
这是 Spring Boot 整合 Thymeleaf 的几个关键点,关于 Thymeleaf 这个页面模板自己更多的用法,你们能够参考 Thymeleaf 的文档:www.thymeleaf.org。
本文主要向你们简单介绍了 Spring Boot 和 Thymeleaf 整合时的几个问题,仍是比较简单的,你们能够阅读 Thymeleaf 官方文档学习 Thymeleaf 的更多用法。本文案例我已上传到 GitHub :github.com/lenve/javab…
关于本文,有问题欢迎留言讨论。
关注公众号【江南一点雨】,专一于 Spring Boot+微服务以及先后端分离等全栈技术,按期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!