SpringBoot学习笔记五:整合Thymeleaf模板

thymeleaf介绍

Thymeleaf是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf的语法更加接近HTML,并且具有很高的扩展性。详细资料可以浏览官网

Thymeleaf官网

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的自动配置功能ThymeleafAutoConfigurationSpring 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语法可参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,104评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,816评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,697评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,836评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,851评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,441评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,992评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,899评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,457评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,529评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,664评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,346评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,025评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,511评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,611评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,081评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,675评论 2 359

推荐阅读更多精彩内容