SpringBoot学习笔记五:整合Thymeleaf模板
2018-07-06 本文已影响42人
fulgens
thymeleaf介绍
Thymeleaf
是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf
的语法更加接近HTML,并且具有很高的扩展性。详细资料可以浏览官网。
Thymeleaf特点
- 支持无网络环境下运行,由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。所以它可以让前端小姐姐在浏览器中查看页面的静态效果,又可以让程序员小哥哥在服务端查看带数据的动态页面效果。
- 开箱即用,为Spring提供方言,可直接套用模板实现JSTL、 OGNL表达式效果,避免每天因套用模板而修改JSTL、 OGNL标签的困扰。同时开发人员可以扩展自定义的方言。
- SpringBoot官方推荐模板,提供了可选集成模块(spring-boot-starter-thymeleaf),可以快速的实现表单绑定、属性编辑器、国际化等功能。
Spring Boot整合Thymeleaf
题外话:在Spring Boot
出现之前整合Thymeleaf
你可能需要配置如下的Bean
(采用Java Config
)
@Bean
// 配置模板解析器
// Thymeleaf3使用ITemplateResolver接口,SpringResourceTemplateResolver实现类
// Thymeleaf3之前使用TemplateResolver接口,ServletContextTemplateResolver实现类
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver =
new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// 设置templateMode属性为HTML5
templateResolver.setTemplateMode("HTML5");
// 设置编码格式为UTF-8
templateResolver.setCharacterEncoding("UTF-8");
// templateResolver.setOrder(1);
// templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// 注入模板解析器
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
@Bean
@Primary
public ViewResolver viewResolver(TemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
得益于Spring Boot
的自动配置功能ThymeleafAutoConfiguration,Spring Boot
整合Thymeleaf
很便捷
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置
application.yml
spring:
thymeleaf:
cache: false
encoding: UTF-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
servlet:
content-type: text/html
这里需要注意的是Spring Boot默认情况下会缓存模板
spring.thymeleaf.cache=true
,一般在开发时需要将此项设置为false
,在部署时再将此值设置为true
,以提高性能,但Spring Boot也提供了devtools开发者工具,默认情况下devtools会禁用缓存选项
,因此使用devtools进行热部署便不用更改spring.thymeleaf.cache
的默认配置了,也不要在全局配置文件配置为true
关于devtools的使用可参考我的文章 SpringBoot学习笔记三:devtools与热部署
这里贴出Spring Boot关于Thymeleaf的所有配置项(引自官方文档)
# THYMELEAF
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0 # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.
Thymeleaf实践
PageController
package com.example.springbootthymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/regist")
public String toRegistPage(Model model) {
model.addAttribute("title", "用户注册");
model.addAttribute("msg", "欢迎注册");
return "regist";
}
}
src/main/resources/templates/regist.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">用户注册</title>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form class="col-md-4 col-md-offset-4" th:action="@{/regist}"
method="post">
<fieldset>
<legend th:text="${msg}">欢迎注册</legend>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-user"></span>
<input id="username" name="username" class="form-control"
placeholder="请输入用户名"/>
</div>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-lock"></span>
<input type="password" id="password" name="password" class="form-control"
placeholder="请输入密码"/>
</div>
<div class="input-group form-group">
<span class="input-group-addon glyphicon glyphicon-envelope"></span>
<input id="email" name="email" class="form-control"
placeholder="请输入邮箱账号"/>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="reset" class="btn btn-default btn-primary">重置</button>
<button type="submit" class="btn btn-default btn-primary">注册</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</body>
</html>
静态效果
在系统资源管理器找到regist.html双击即可打开
静态效果
动态效果
启动工程访问http://localhost:8080/regist
Thymeleaf语法可参考