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

x33g5p2x  于2021-12-25 转载在 Java  
字(5.9k)|赞(0)|评价(0)|浏览(340)

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

1、Thymeleaf 官网:https://www.thymeleaf.org/

2、Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf

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>

2、渲染流程规则可以从它的自动配置文件查看:

/**
 * 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;

1、默认前缀:DEFAULT_PREFIX = "classpath:/templates/"
2、默认后缀:DEFAULT_SUFFIX = ".html"

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

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

# 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.

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

/**
     * http://localhost:8080/user/toHome
     * @param model
     * @return
     */
    @GetMapping("/user/toHome")
    public String toHome(Model model) {
        //向页面返回的数据
        model.addAttribute("code", 200);
        model.addAttribute("msg", "管理员向你表示祝贺!");
        //自动跳转到默认的 classpath:/templates/home.html 页面
        return "home";
    }

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

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
状态码:<span th:text="${code}"></span><br>
消息:<span th:text="${msg}"></span>
</body>
</html>

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

静态资源映射规则

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/

配置应用首页

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 版本

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 官网下载:http://www.webjars.org/

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

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

相关文章

微信公众号

最新文章

更多