【模板引擎】SpringBoot:thymeleaf模板引擎

SpringBoot:thymeleaf模板引擎

1. webjars&静态资源映射规则

SpringBoot 项目使用 Maven 构建,导入 web 模块,pom.xml文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jiker</groupId>
    <artifactId>springboot-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-web</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

若是原来的web应用时,应用中的静态资源将放在webapp目录下
如今,项目打包方式为 jar ,若需要放入静态资源文件,则需要了解 SpringBoot 的静态资源映射规则

Spring Boot 应用中,SpringMVC 的相关配置都是在 WebMvcAutoConfiguration
查看该类源码一部分

 public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
       	if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

    }
}

该方法名为 addResourceHandlers:添加资源映射

规则1、所有 /webjars/** 请求,都去 classpath:/META-INF/resources/webjars/ 下寻找资源
webjars:以 jar 包的方式引入资源,参考:https://www.webjars.org/
例子:若项目中需要引入 jQuery ,原 Web 应用的方式是将 jQuery.js 文件导入到 webapp文件夹中
现在可以通过 webjars,以 jar 包的方式导入 jQuery
在官网中搜索需要的插件
在这里插入图片描述
将依赖导入进 pom.xml 文件中

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--导入jQuery依赖-->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

查看依赖
在这里插入图片描述
发现该文件夹目录已经和映射规则 classpath:/META-INF/resources/webjars/ 对应
即,现可以发送:http://localhost:8080/webjars/jquery/3.3.1/jquery.js 查看 jquery 源码
在这里插入图片描述
规则2、“/**” 访问当前项目的任何资源(静态资源文件夹)
在源码中的另一个规则 String staticPathPattern = this.mvcProperties.getStaticPathPattern();获取静态资源路径
该方法的源码如下

public String getStaticPathPattern() {
    return this.staticPathPattern;
}

public class WebMvcProperties {
    private Format messageCodesResolverFormat;
    private Locale locale;
    private WebMvcProperties.LocaleResolver localeResolver;
    private String dateFormat;
    private boolean dispatchTraceRequest;
    private boolean dispatchOptionsRequest;
    private boolean ignoreDefaultModelOnRedirect;
    private boolean throwExceptionIfNoHandlerFound;
    private boolean logResolvedException;
    private String staticPathPattern;
    private final WebMvcProperties.Async async;
    private final WebMvcProperties.Servlet servlet;
    private final WebMvcProperties.View view;
    private final WebMvcProperties.Contentnegotiation contentnegotiation;
    private final WebMvcProperties.Pathmatch pathmatch;

    public WebMvcProperties() {
        this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER;
        this.dispatchTraceRequest = false;
        this.dispatchOptionsRequest = true;
        this.ignoreDefaultModelOnRedirect = true;
        this.throwExceptionIfNoHandlerFound = false;
        this.logResolvedException = false;
        this.staticPathPattern = "/**";
        this.async = new WebMvcProperties.Async();
        this.servlet = new WebMvcProperties.Servlet();
        this.view = new WebMvcProperties.View();
        this.contentnegotiation = new WebMvcProperties.Contentnegotiation();
        this.pathmatch = new WebMvcProperties.Pathmatch();
    }
	
	... ...

即默认路径为 this.staticPathPattern = "/**";
通过 getStaticLocations() 方法源码可知

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

若访问 http://localhost:8080/xxx 无任何处理时,则去以下文件夹下寻找资源

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/ : 当前项目的根路径

即可以将 cssjsimg 等文件放在以下目录中
在这里插入图片描述
规则3、首页;静态资源文件夹下所有的 index.html 页面;被 “/**” 映射
同样在 WebMvcAutoConfiguration 中查看以下源码

	//配置首页映射
	@Bean
    public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
        return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
    }

	//WelcomePageHandlerMapping 方法
	WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
        if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage.get());
            this.setRootViewName("forward:index.html");
        } else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
            logger.info("Adding welcome page template: index");
            this.setRootViewName("index");
        }

    }

在静态资源文件夹中创建一个 index 页面,之后通过 http://localhost:8080/ 进行访问
在这里插入图片描述
在这里插入图片描述
首页 index.html 得到映射

规则4、所有的 **/favicon.ico 都是在静态资源文件夹中映射(配置网页图标)

		//配置网页图标
        @Configuration
        @ConditionalOnProperty(
            value = {"spring.mvc.favicon.enabled"},
            matchIfMissing = true
        )
        public static class FaviconConfiguration implements ResourceLoaderAware {
            private final ResourceProperties resourceProperties;
            private ResourceLoader resourceLoader;

            public FaviconConfiguration(ResourceProperties resourceProperties) {
                this.resourceProperties = resourceProperties;
            }

            public void setResourceLoader(ResourceLoader resourceLoader) {
                this.resourceLoader = resourceLoader;
            }

            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(-2147483647);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
                return mapping;
            }

            @Bean
            public ResourceHttpRequestHandler faviconRequestHandler() {
                ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
                requestHandler.setLocations(this.resolveFaviconLocations());
                return requestHandler;
            }

            private List<Resource> resolveFaviconLocations() {
                String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
                List<Resource> locations = new ArrayList(staticLocations.length + 1);
                Stream var10000 = Arrays.stream(staticLocations);
                ResourceLoader var10001 = this.resourceLoader;
                var10001.getClass();
                var10000.map(var10001::getResource).forEach(locations::add);
                locations.add(new ClassPathResource("/"));
                return Collections.unmodifiableList(locations);
            }
        }

从网上下载一个 .ico 文件当作图标:https://www.easyicon.net/
在静态资源文件夹中引入网页图标
在这里插入图片描述

2. 引入thymeleaf模板引擎

Spring Boot 推荐使用 Thymeleaf 模板引擎
官网:https://www.thymeleaf.org/

1、引入thymeleaf模板引擎

	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

2、thymeleaf使用&语法
查看 ThymeleafProperties 源码默认规则

... ...
@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";

只要我们把 HMTL 页面放在 classpath:/templates/ 文件夹下,Thymeleaf 就能自动渲染

测试
templates 文件夹中创建 success.html ,创建一个控制器访问

package com.jiker.springbootweb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/success")
    public String success(){
        //classpath:/templates/success.html
        return "success";
    }
}

在这里插入图片描述
访问成功

使用语法:
1、导入 thymeleaf 名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2、使用示例

package com.jiker.springbootweb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

@Controller
public class HelloController {

    @GetMapping("/success")
    public String success(Map<String,String> map){
        map.put("thymeleaf","模板引擎");
        //classpath:/templates/success.html
        return "success";
    }
}

在 html 页面中取出值

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>success</h1>
    <div th:text="${thymeleaf}"></div>
</body>
</html>

更多语法示例,详见参考文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

时间:2019.6.11 20:17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值