2、SpringBoot模板引擎Thymeleaf使用


前言

1.Thymeleaf是一个Java库。它是一个基于XML/XHTML/HTML5的模板引擎,能够对模板文件执行一组变换从而使其能够展现应用生成的数据和文本。
2.它非常适用于Web应用中的XHTML/HTML5页面,同时它也能处理任何XML文件,无论是在web应用还是在独立应用中。
3.Thymeleaf的主要目标是提供一种优雅并格式良好的创建模板的的方法。为了达成这个目标,它被设计为使用XML标签和属性来定义需要在DOM (Document Object Model) 上执行的逻辑,而不是直接在模板中显式的写逻辑代码。
4.Thymeleaf架构借助智能缓存已经解析的文件,使得需要进行的I/O操作最小化,达到快速处理模板的目标。
5.除此以外,Thymeleaf从一开始就以XML和WEB标准作为设计基础,让你能够按需构建完全校验化的模板。
6.在早期开发的时候,我们完成的都是静态页面也就是html页面,随着时间轴的发展,慢慢的引入了jsp页面,当在后端服务查询到数据之后可以转发到jsp页面,可以轻松的使用jsp页面来实现数据的显示及交互,jsp有非常强大的功能,但是,在使用springboot的时候,整个项目是以jar包的方式运行而不是war包,而且还嵌入了Tomcat容器,因此,在默认情况下是不支持jsp页面的。如果直接以纯静态页面的方式会给我们的开发带来很大的麻烦,SpringBoot推荐使用模板引擎。

一、Thymeleaf简介

Thymeleaf支持处理六种类型的模板,每一种模板被称为模板模式(Template Mode)。
HTML、XML、TEXT、JAVASCRIPT、CSS、RAW
中文文档:打开链接

二、使用步骤

1.通过Idea开发工具构建

  1. 选择Spring Initializr来快速构建一个SpringBoot 项目。本示例使用的JDK1.8和Maven。 在这里插入图片描述
  2. 选择Template Engines 勾选Thymeleaf,点击下一步完成构建操作
    在这里插入图片描述

2.导入Maven依赖

配置如下:

        <!--thymeleaf模板-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

3.新建Controller控制类

代码如下(示例):

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafController {
    @RequestMapping("/hello")
    public String hello1(Model model) {
        model.addAttribute("msg", "hahahaha");
        return "hello2";
    }
}

4.在目录templates中新建html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
显示消息为:<p th:text="${msg}"></p>
</body>
</html>

5.核心配置类ThymeleafProperties

package org.springframework.boot.autoconfigure.thymeleaf;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.util.MimeType;
import org.springframework.util.unit.DataSize;
@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    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 = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
    private Integer templateResolverOrder;
    private String[] viewNames;
    private String[] excludedViewNames;
    private boolean enableSpringElCompiler;
    private boolean renderHiddenMarkersBeforeCheckboxes;
    private boolean enabled;
    private final ThymeleafProperties.Servlet servlet;
    private final ThymeleafProperties.Reactive reactive;

    public ThymeleafProperties() {
        this.encoding = DEFAULT_ENCODING;
        this.cache = true;
        this.renderHiddenMarkersBeforeCheckboxes = false;
        this.enabled = true;
        this.servlet = new ThymeleafProperties.Servlet();
        this.reactive = new ThymeleafProperties.Reactive();
    }

    public boolean isEnabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isCheckTemplate() {
        return this.checkTemplate;
    }
    public void setCheckTemplate(boolean checkTemplate) {
        this.checkTemplate = checkTemplate;
    }
    public boolean isCheckTemplateLocation() {
        return this.checkTemplateLocation;
    }
    public void setCheckTemplateLocation(boolean checkTemplateLocation) {
        this.checkTemplateLocation = checkTemplateLocation;
    }

    public String getPrefix() {
        return this.prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return this.suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public String getMode() {
        return this.mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public Charset getEncoding() {
        return this.encoding;
    }

    public void setEncoding(Charset encoding) {
        this.encoding = encoding;
    }

    public boolean isCache() {
        return this.cache;
    }

    public void setCache(boolean cache) {
        this.cache = cache;
    }

    public Integer getTemplateResolverOrder() {
        return this.templateResolverOrder;
    }

    public void setTemplateResolverOrder(Integer templateResolverOrder) {
        this.templateResolverOrder = templateResolverOrder;
    }

    public String[] getExcludedViewNames() {
        return this.excludedViewNames;
    }

    public void setExcludedViewNames(String[] excludedViewNames) {
        this.excludedViewNames = excludedViewNames;
    }

    public String[] getViewNames() {
        return this.viewNames;
    }

    public void setViewNames(String[] viewNames) {
        this.viewNames = viewNames;
    }

    public boolean isEnableSpringElCompiler() {
        return this.enableSpringElCompiler;
    }

    public void setEnableSpringElCompiler(boolean enableSpringElCompiler) {
        this.enableSpringElCompiler = enableSpringElCompiler;
    }
    public boolean isRenderHiddenMarkersBeforeCheckboxes() {
        return this.renderHiddenMarkersBeforeCheckboxes;
    }
    public void setRenderHiddenMarkersBeforeCheckboxes(boolean renderHiddenMarkersBeforeCheckboxes) {
        this.renderHiddenMarkersBeforeCheckboxes = renderHiddenMarkersBeforeCheckboxes;
    }
    public ThymeleafProperties.Reactive getReactive() {
        return this.reactive;
    }
    public ThymeleafProperties.Servlet getServlet() {
        return this.servlet;
    }
    static {
        DEFAULT_ENCODING = StandardCharsets.UTF_8;
    }
    public static class Reactive {
        private DataSize maxChunkSize = DataSize.ofBytes(0L);
        private List<MediaType> mediaTypes;
        private String[] fullModeViewNames;
        private String[] chunkedModeViewNames;
        public Reactive() {
        }
        public List<MediaType> getMediaTypes() {
            return this.mediaTypes;
        }
        public void setMediaTypes(List<MediaType> mediaTypes) {
            this.mediaTypes = mediaTypes;
        }

        public DataSize getMaxChunkSize() {
            return this.maxChunkSize;
        }
        public void setMaxChunkSize(DataSize maxChunkSize) {
            this.maxChunkSize = maxChunkSize;
        }
        public String[] getFullModeViewNames() {
            return this.fullModeViewNames;
        }

        public void setFullModeViewNames(String[] fullModeViewNames) {
            this.fullModeViewNames = fullModeViewNames;
        }
        public String[] getChunkedModeViewNames() {
            return this.chunkedModeViewNames;
        }

        public void setChunkedModeViewNames(String[] chunkedModeViewNames) {
            this.chunkedModeViewNames = chunkedModeViewNames;
        }
    }
    public static class Servlet {
        private MimeType contentType = MimeType.valueOf("text/html");
        private boolean producePartialOutputWhileProcessing = true;
        public Servlet() {
        }
        public MimeType getContentType() {
            return this.contentType;
        }
        public void setContentType(MimeType contentType) {
            this.contentType = contentType;
        }
        public boolean isProducePartialOutputWhileProcessing() {
            return this.producePartialOutputWhileProcessing;
        }
        public void setProducePartialOutputWhileProcessing(boolean producePartialOutputWhileProcessing) {
            this.producePartialOutputWhileProcessing = producePartialOutputWhileProcessing;
        }
    }
}

6.测试结果

在这里插入图片描述

三、扩展使用

1. 常用属性th使用

th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3​ th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4​ th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

添加方法:

@RequestMapping("/thymeleaf")
    public String thymeleaf(ModelMap map){
        map.put("thText","th:text设置文本内容 <b>加粗</b>");
        map.put("thUText","th:utext 设置文本内容 <b>加粗</b>");
        map.put("thValue","thValue 设置当前元素的value值");
        map.put("thEach","Arrays.asList(\"th:each\", \"遍历列表\")");
        map.put("thIf","msg is not null");
        map.put("thObject",new Person("zhangsan",12,"男"));
        return "thymeleaf";
    }

添加页面thymeleaf.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${thText}"></p>
<p th:utext="${thUText}"></p>
<input type="text" th:value="${thValue}">
<div th:each="message:${thEach}">
    <p th:text="${message}"></p>
</div>
<div>
    <p th:text="${message}" th:each="message:${thEach}"></p>
</div>
<p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
<div th:object="${thObject}">
    <p>name:<span th:text="*{name}"/></p>
    <p>age:<span th:text="*{age}"/></p>
    <p>gender:<span th:text="*{gender}"/></p>
</div>
</body>
</html>

测试结果:
在这里插入图片描述

2. 标准表达式语法使用

${…} 变量表达式,Variable Expressions
​*{…} 选择变量表达式,Selection Variable Expressions
可以获取对象的属性和方法。
可以使用ctx,vars,locale,request,response,session,servletContext内置对象。

session.setAttribute("user","zhangsan");
th:text="${session.user}"

可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法。

添加方法:

  @RequestMapping("standardExpression")
    public String standardExpression(ModelMap map){
        map.put("Str", "Blog");
        map.put("Bool", true);
        map.put("Array", new Integer[]{1,2,3,4});
        map.put("List", Arrays.asList(1,3,2,4,0));
        Map hashMap = new HashMap();
        hashMap.put("thName", "${#...}");
        hashMap.put("desc", "变量表达式内置方法");
        map.put("Map", hashMap);
        map.put("Date", new Date());
        map.put("Num", 888.888D);
        return "standardExpression";
    }

添加页面standardExpression.html:

<!--
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
二、numbers:数值格式化方法,常用的方法有:formatDecimal等
三、bools:布尔方法,常用的方法有:isTrue,isFalse等
四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等
-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf内置方法</title>
</head>
<body>
    <h3>#strings </h3>
    <div th:if="${not #strings.isEmpty(Str)}" >
        <p>Old Str : <span th:text="${Str}"/></p>
        <p>toUpperCase : <span th:text="${#strings.toUpperCase(Str)}"/></p>
        <p>toLowerCase : <span th:text="${#strings.toLowerCase(Str)}"/></p>
        <p>equals : <span th:text="${#strings.equals(Str, 'blog')}"/></p>
        <p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(Str, 'blog')}"/></p>
        <p>indexOf : <span th:text="${#strings.indexOf(Str, 'r')}"/></p>
        <p>substring : <span th:text="${#strings.substring(Str, 2, 4)}"/></p>
        <p>replace : <span th:text="${#strings.replace(Str, 'it', 'IT')}"/></p>
        <p>startsWith : <span th:text="${#strings.startsWith(Str, 'it')}"/></p>
        <p>contains : <span th:text="${#strings.contains(Str, 'IT')}"/></p>
    </div>
    <h3>#numbers </h3>
    <div>
        <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(Num, 0, 2)}"/></p>
        <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(Num, 5, 2)}"/></p>
    </div>

    <h3>#bools </h3>
    <div th:if="${#bools.isTrue(Bool)}">
        <p th:text="${Bool}"></p>
    </div>

    <h3>#arrays </h3>
    <div th:if="${not #arrays.isEmpty(Array)}">
        <p>length : <span th:text="${#arrays.length(Array)}"/></p>
        <p>contains : <span th:text="${#arrays.contains(Array,2)}"/></p>
        <p>containsAll : <span th:text="${#arrays.containsAll(Array, Array)}"/></p>
    </div>
    <h3>#lists </h3>
    <div th:if="${not #lists.isEmpty(List)}">
        <p>size : <span th:text="${#lists.size(List)}"/></p>
        <p>contains : <span th:text="${#lists.contains(List, 0)}"/></p>
        <p>sort : <span th:text="${#lists.sort(List)}"/></p>
    </div>
    <h3>#maps </h3>
    <div th:if="${not #maps.isEmpty(hashMap)}">
        <p>size : <span th:text="${#maps.size(hashMap)}"/></p>
        <p>containsKey : <span th:text="${#maps.containsKey(hashMap, 'thName')}"/></p>
        <p>containsValue : <span th:text="${#maps.containsValue(hashMap, '#maps')}"/></p>
    </div>
    <h3>#dates </h3>
    <div>
        <p>format : <span th:text="${#dates.format(Date)}"/></p>
        <p>custom format : <span th:text="${#dates.format(Date, 'yyyy-MM-dd HH:mm:ss')}"/></p>
        <p>day : <span th:text="${#dates.day(Date)}"/></p>
        <p>month : <span th:text="${#dates.month(Date)}"/></p>
        <p>monthName : <span th:text="${#dates.monthName(Date)}"/></p>
        <p>year : <span th:text="${#dates.year(Date)}"/></p>
        <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(Date)}"/></p>
        <p>hour : <span th:text="${#dates.hour(Date)}"/></p>
        <p>minute : <span th:text="${#dates.minute(Date)}"/></p>
        <p>second : <span th:text="${#dates.second(Date)}"/></p>
        <p>createNow : <span th:text="${#dates.createNow()}"/></p>
    </div>
</body>
</html>

测试结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3. ​@{…} 链接表达式,Link URL Expressions

<!--
不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
链接表达式结构
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
-->
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/main/css/123.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

4.​#{…} 消息表达式,Message Expressions

消息表达式一般用于国际化的场景。结构:th:text=“#{msg}”

5. ~{…} 代码块表达式,Fragment Expressions

<!--
支持两种语法结构
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路:/resources/templates/templatename.html,要注意文件的路径。
fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式的使用
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,
-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:fragment定义代码块标识-->
<footer th:fragment="copy">
    2019 The Good Thymes Virtual Grocery
</footer>
<!--三种不同的引入方式-->
<div th:insert="fragment::copy"></div>
<div th:replace="fragment::copy"></div>
<div th:include="fragment::copy"></div>
<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
    <footer>
        &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>

总结

语法的功能还是比较丰富多样,类似JSTL、EL、Struts语法的使用。thymeleaf是SpringBoot推荐使用的模版引擎。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用Spring Boot框架时,我们可以使用Thymeleaf模板引擎来渲染HTML页面。Thymeleaf是一种面向服务器的模板引擎,它可以用来构建与Web标准兼容的HTML5页面。 在Spring Boot中,我们首先需要在pom.xml文件中添加Thymeleaf依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 在Spring Boot应用程序中,我们需要配置Thymeleaf的视图解析器。可以在application.properties文件中添加以下属性: ``` spring.thymeleaf.enabled=true spring.thymeleaf.cache=false ``` 可以看到,我们打开了Thymeleaf的缓存机制,以便更方便地测试HTML页面的更改。然后,我们需要在我们的Spring Boot应用程序中创建一个控制器,以便为HTML页面提供服务: ``` @Controller public class MyController { @GetMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 在上面的控制器中,我们使用@GetMapping注释来将应用程序映射到“/”路径。然后,我们将一个消息添加到Model中,以便将其传递给Thymeleaf视图。最后,我们返回视图名称“index”,这将是我们要渲染的HTML页面。 在Thymeleaf模板中,我们可以使用th:text属性来将消息添加到HTML页面中: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello, Thymeleaf</title> </head> <body> <h1 th:text="${message}">Hello, World!</h1> </body> </html> ``` 在上面的示例中,我们使用th:text属性来向页面添加消息。可以看到,我们使用Thymeleaf的EL表达式来获取控制器中传递的消息。 使用了这些步骤后,当我们访问应用程序的根目录时,会渲染index.html页面,并将消息“Hello, Thymeleaf!”添加到页面中。这就是如何在Spring Boot应用程序中使用Thymeleaf模板引擎来渲染HTML页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追风★少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值