Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」目录本文导读模板引擎SpringBoot使用Thymeleaf引入Thymeleaf渲染流程规则后台控制层前台页面浏览器访问本文导读1、本文承接《SpringBootWeb开发简介及webajrs和静态资源映射规则》,以里面的“dog”项目进行本次学习2、以前开发web项目时,只需将静态的"html”页面后缀名修改为“jsp”,…

大家好,欢迎来到IT知识分享网。

目录

Thymeleaf 模板引擎概述

Thymeleaf 官方文档下载

Spring Boot 渲染 Thymeleaf  规则

Spring Boot 集成 Thymeleaf  快速入门 

静态资源映射规则

配置应用首页

WebJars 管理前端 jar 版本


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 也有自己的语法.

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」

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 快速入门、静态资源映射规则、WebJars「终于解决」

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

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」


静态资源映射规则

本节与 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/”

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」

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 为例:

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」

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

Spring Boot 集成 Thymeleaf 快速入门、静态资源映射规则、WebJars「终于解决」

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/24248.html

(0)
上一篇 2023-08-25 09:45
下一篇 2023-08-30 19:45

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信