Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars

目录

Thymeleaf 模板引擎概述

Thymeleaf 官方文档下载

Spring Boot 渲染 Thymeleaf  规则

Spring Boot 集成 Thymeleaf  快速入门 

静态资源映射规则

配置应用首页

WebJars 管理前端 jar 版本

Thymeleaf 公共部分抽取

thymeleaf 模板布局概述

thymeleaf 公共部分抽取

thymeleaf 链接动态高亮显示


Thymeleaf 模板引擎概述

1、以前开发 web 项目时,只需将静态的 ".html” 页面后缀名修改为“.jsp”,然后在文件中加入 jsp 页面标识即可做 jsp 开发,然而 Spring Boot 项目采用打 jar 包的方式,默认使用的是内置的 Tomcat 服务器,所以默认是不支持 jsp 的,但可以使用其它的模板引擎。

2、市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf 等等。

3、JSP 本质也是模板引擎,Spring Boot 官方支持:Thymeleaf Templates、FreeMarker Templates、Groovy Templates 等模板引擎。

4、模板引擎原理图如下,模板引擎的作用都是将模板(页面)和数据进行整合然后输出显示,区别在于不同的模板使用不同的语法,如 JSP 的 JSTL 表达式,以及 JSP 自己的表达式和语法,同理 Thymeleaf 也有自己的语法.

Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。
Thymeleaf 的主要目标是提供一种优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。这改善了设计的沟通,弥补了设计和开发团队之间的差距。
Thymeleaf 也从一开始就设计了Web标准 - 特别是 HTML5 - 允许您创建完全验证的模板,Spring Boot 官方推荐使用  thymeleaf 而不是 JSP。
Spring Boot 中使用 Thymeleaf  模板引擎时非常简单,因为 Spring Boot 已经提供了默认的配置,比如解析的文件前缀,文件后缀,文件编码,缓存等等,程序员需要的只是写 html 中的内容即可。

Thymeleaf 官网:Thymeleaf

https://github.com/thymeleaf/thymeleaf

Thymeleaf 官方文档下载

https://www.thymeleaf.org/documentation.html

Spring Boot 渲染 Thymeleaf  规则

1、渲染流程规则可以从它的自动配置属性文件 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 查看:

/**
 * Properties for Thymeleaf.
 * @author Stephane Nicoll
 * @author Brian Clozel
 * @author Daniel Fernández
 * @author Kazuki Shimizu
 * @since 1.2.0
 */
@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";
	/**
	 * Whether to check that the template exists before rendering it.
	 */
	private boolean checkTemplate = true;
  • 默认前缀:DEFAULT_PREFIX = "classpath:/templates/"
  • 默认后缀:DEFAULT_SUFFIX = ".html"

2、所以默认只要把 HTML 页面放在 classpath:/templates/ 下,thymeleaf 模板引擎就能自动渲染, classpath:/templates/ 目录以外的 html 文件是无法使用 Thymeleaf 引擎的。

3、可以在全局配置文件中修改这些规则, 官方文档配置

# THYMELEAF (ThymeleafAutoConfiguration)
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.

4、templates 为模板目录,只有使用 templateaf 模板引擎时才有用,模板目录中的文件(如 *.html)从浏览器是无法直接访问的(index.html 首页地址除外),相当于以前的 WEB-INF目录下的文件无法直接访问一样,必须通过后台才能访问它'静态资源目录'不一样,静态资源目录中的文件从浏览器是可以直接访问的,而且与模板引擎无关。 

Spring Boot 集成 Thymeleaf  快速入门 

 1、使用 Thymeleaf 同样第一步在 pom.xml 引入  spring-boot-starter-thymeleaf 模块(Starters):

        <!-- 引入thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

pom.xml · 汪少棠/jpaTransactional - Gitee.com

如果在 IDEA 创建项目的时候勾选了 Thymeleaf 模板引擎依赖,则 IDEA 构建项目的时候自动会在 resources 下新建 templates 模板目录,没有时也没关系,手动新建即可。

2、后台控制台提供一个接口,浏览器访问后,跳转到模板目录下的 .html 文件,同时向他传递数据过去显示。

    /**
     * http://localhost:8080/thymeleaf/home
     *
     * @param responseMap
     * @return
     */
    @RequestMapping("thymeleaf/home")
    public String goHome(Map<String, Object> responseMap, Model model) {
        // 向页面返回数据方式1:默认 responseMap 的内容会放到请求域中,调整后的新页面上可以直接使用 Thymeleaf 表达式取值
        responseMap.put("name", "张三");
        responseMap.put("age", 35);

        // 向页面返回数据方式2:使用 org.springframework.ui.Model 向页面返回数据
        model.addAttribute("code", 200);
        model.addAttribute("msg", "管理员向你表示祝贺!");

        // 全部基于 Spring Boot 给 Thymeleaf 的默认配置
        // 自动跳转到默认的 classpath:/templates/home.html 页面
        return "home";
    }

src/main/java/com/wmx/controller/ThymeleafController.java · 汪少棠/jpaTransactional - Gitee.com

3、前端 .html 页面中的 <html> 标签加上 xmlns:th="http://www.thymeleaf.org" 属性,IDEA 编辑器就会有 Thymeleaf 语法提示,不写不影响运行。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<h3>Spring Boot 集成 Thymeleaf 快速入门 </h3>
<!--Thymeleaf 语法取值-->

<p>姓名:<span th:text="${name}">未知</span></p>
<p>年龄:[[${age}]]</p>

<p>状态码:<span th:text="${code}"></span></p>
<p>消息:[[${msg}]]</p>

</body>
</html>

 src/main/resources/templates/home.html · 汪少棠/jpaTransactional - Gitee.com

 th:text 是 Thymeleaf 其中的一个取值语法之一,关于 Thymeleaf 的详细语法可以参考 hymeleaf


静态资源映射规则

本节与 Thymeleaf 知识点没有关系,是单独的知识点。

1、Spring boot 静态资源映射规则可以在“org.springframework.boot.autoconfigure.web”包下面的“ResourceProperties”类中找到

@ConfigurationProperties(
    prefix = "spring.resources",    ignoreUnknownFields = false
)
public class ResourceProperties {
//可以设置和静态资源有关的参数,如缓存时间等

2、ResourceProperties 类中约定如下,即应用中的静态资源默认都是从类路径下的以下约定目录中按优先级顺序进行寻找:

	private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };
	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

3、当浏览器页面需要获取静态资源时,会默认按照约定进行逐个查找,直到找到或者全部检索完,优先级从上至下由高到低

  • "classpath:/META‐INF/resources/",
  • "classpath:/resources/",
  • "classpath:/static/",
  • "classpath:/public/"

4、如果想要修改静态资源位置,则可以使用 spring.resources.static-locations 配置(更多 spring.resources.* 配置参考官网):

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

配置应用首页

本节与 Thymeleaf 知识点没有关系,是单独的知识点。

1、欢迎页即应用首页,默认映射静态资源文件夹下的 index.html 页面作为首页。

2、“localhost:8080/应用上下文路径 ” 此时默认找 index.index 页面作为首页

3、四大静态资源目录下的资源,浏览器都可以直接访问,其中默认以 index.html 为应用首页,当引入了 thymeleaf 模板引擎后,应用首页 index.html 也可以放在 templates 目录下,浏览器输入 "http://ip:port/应用上下文" 同样可以进入。

4、templates 为模板目录,其中的文件(如 *.html)从浏览器是无法直接访问的(index.html除外),相当于以前的 WEB-INF目录下的文件无法直接访问一样,必须通过后台才能访问。

WebJars 管理前端 jar 版本

本节与 Thymeleaf 知识点没有关系,是单独的知识点。

1、Web 前端使用了越来越多的JS或CSS,如 jQuery、Bootstrap 等,一般情况下,将这些 Web 资源拷贝到 Java Web 项目的webapp 相应目录下进行管理。

2、WebJars 是将 web 前端资源(js,css等)打成 jar 包文件,然后借助 Maven 工具,以 jar 包形式对 web 前端资源进行统一依赖管理,保证这些 Web 资源版本唯一性。

3、WebJars 的 jar 包部署在 Maven 中央仓库上,可以从 WebJars 官网下载:WebJars - Web Libraries in Jars

4、使用起来非常简单,就像后台依赖一样,在 pom.xml 中导入前端依赖即可,下面以 JQuery 为例:

5、“META-INF/resources” 目录是 Spring Boot 约定的类路径下的静态资源默认访问目录,所以访问 webJars 的时候不要再路径中加上前缀 “META-INF/resources”,而是直接从“webjars”层级开始。

Thymeleaf 公共部分抽取

thymeleaf 模板布局概述

1、一个系统中各个页面的头部、底部、左侧或右侧通常都是一致的,不需要每个页面都重复写,而应该提取出来,大家各自引用。好处就是能大大的减少代码量,以及修改时不再需要每隔页面再去修改。

2、JSP 可以使用 <jsp:include page=” ”...动态包含,Thymeleaf 可以使用 th:fragment + th:replace 。

3、假设应用中需要一个公用的底部模板 html 文件为 /templates/commonsFooter.html,使用 th:fragment 将其抽取为一个名字叫 "copy" 的代码片段,以后在其它需要引用的地方可以使用 th:insert 、th:replace、th:include 等进行引用。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy">
     网站标识码bm0100001 京ICP备05070218号 京公网安备11010202000001号
</div>
</body>
</html>

4、三种引入公共片段的 th 属性:

  1. <div th:insert="commonsFooter:: selector|fragmentname"></div>:将公共片段整个插入到声明引入的元素中
  2. <div th:replace="commonsFooter:: selector|fragmentname"></div>:将声明引入的元素替换为公共片段
  3. <div th:include="commonsFooter:: selector|fragmentname"></div>:将被引入的片段的内容包含进这个标签中
  4. 注意:commonsFooter 是模板 html 文件名称,selector 是选择器,如标签的 id 值等;fragmentname 就是 th:fragment 声明的片段名称
<!--1、比如抽取的公用代码片段如下-->
<footer th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>

<!--2、采用如下三种方式进行引用-->
<div th:insert="commonsFooter::copy"></div>
<div th:replace="commonsFooter::copy"></div>
<div th:include="commonsFooter::copy"></div>

<!--3、则三种引用方式的效果分别对应如下-->
<div>
    <footer>
        &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>

<footer>
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>

<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>

thymeleaf 公共部分抽取

环境:Java jdk 1.8 +Spring boot 2.1.3 + Thymeleaf。

1、上面是 Thymeleaf 的语法介绍,详细信息可以参考《Thymeleaf 模板布局 th:fragment、th:replace、th:insert、th:remove

现在正式开始使用。

一:抽取公共元素

1、对于各页面中公共的头部、底部、左侧、右侧代码使用一个单独的 .html 文件来放置,源码:/commonsTemplate.html

2、/templates/commonsTemplate.html  中抽取了公共的头部、底部内容,同理还可以抽取公共的样式与 js 等内容。

3、公共模板中使用 th:fragment="commonsHead" 标识头部片段, th:fragment="commonsFooter" 标识公共的底部片段,除此之外也可以使用 id、或者 class 来标识。

4、公共模板(.html)必须在 templates 目录下,否则引用时会找不到,一个文件里面可以定义任意多个 th:fragment 片段。

二:引用公共元素

1、在需要引用的位置使用 th:replace 表达式进行引用,源码 /templates/examples/httpPut.html

2、如 <div th:replace="commonsTemplate::commonsFooter"></div> 表示引用 template 目录下 commonsTemplate.html 文件中的 th:fragment="commonsFooter" 定义的片段.

3、在任何需要引用的页面,都可以使用 th:replace 进行引用,让模板片段替换自己。

thymeleaf 链接动态高亮显示

1、对于菜单栏或者导航栏,用户点击某个栏目的时候,跳转到此页面的同时还应该让此栏目高亮显示进行提醒。

2、Thymeleaf 实现链接动态高亮需要使用参数化片段签名功能,即在引入片段的时候传递参数过去,这在以前使用 JSP 动态包含时也是这么做的。

  1. th:fragment 声明片段的时候可以同时声明参数,里面则可以使用这些参数的值.
  2. th:insert、th:replace、th:include 引用片段的时候就可以将参数值传递过去,传值的时候可以直接按顺序传递过去,也可以不按顺序但是按着参数名传递.
8.2 Parameterizable fragment signatures
1) 
    In order to create a more function-like mechanism for template fragments, 
    fragments defined with th:fragment can specify a set of parameters:
<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
2)
    This requires the use of one of these two syntaxes to call the fragment from th:insert or th:replace :
<div th:replace="::frag (${value1},${value2})">...</div>
3)
    Note that order is not important in the last option:
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>
<div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>

3、根据“选择器”进行引用时,是无法声明参数的,所以 th:fragment 也可以不用声明参数,在引用的时候可以直接通过参数名将值传过去使用。

Fragment local variables without fragment arguments
Even if fragments are defined without arguments like this:
<div th:fragment="frag">
    ...
</div>

We could use the second syntax specified above to call them (and only the second one):
<div th:replace="::frag (onevar=${value1},twovar=${value2})">

4、上面是理论介绍,下面正式开始。

一:公共模板片段中定义参数

1、如 <header class="header-area" th:fragment="commonsHead(activeUrl)">:参数名称可以指定多个。

2、指定了参数名称时,th:replace 引用时则必须传递值过来,否则报错。

3、源码:/commonsTemplate.html

二:公共模板片段中使用参数值进行判断

1、如 <li title="http put 请求" th:id="${activeUrl=='httpPut'}?'item-active'">:三元运算符进行条件判断,当条件满足时,为他设置 id 值。

2、这个 id 值会在 css 文件中设置样式,也可以直接添加 class 属性,因为需要覆盖第三方引用的样式,所以才使用了 id 来设置。因 id 引用优先级大于 class 引用。

3、源码:/commonsTemplate.html

#item-active {
    font-size: 150%;
    color: #00aaf3;
}

三:引用公共的模板片段

1、如 <div th:replace="commonsTemplate::commonsHead(httpPut)"></div>:将参数值按顺序传递过去。

2、如果 th:fragment 未定义参数名称,则可以在传递时直接指定,如

<div th:replace="commonsTemplate::commonsHead(activeUrl = 'httpPut')"></div>

3、比如使用 id 选择器时:<div th:replace="commonsTemplate::#commonsHead(activeUrl ='httpPut')"></div>

4、传递的值可以随意定义,在公共模板片段中取值后按着规则判断即可。

5、源码 /templates/examples/httpPut.html

  • 20
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蚩尤后裔-汪茂雄

芝兰生于深林,不以无人而不芳。

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

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

打赏作者

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

抵扣说明:

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

余额充值