SpringBoot+Thymeleaf静态资源的映射规则说明

目录
  • Spring Boot中静态资源的映射规则
    • Thymeleaf模板引擎的映射规则
  • SpringBoot对静态资源的映射规则源码学习笔记

Spring Boot中静态资源的映射规则

Spring Boot中静态资源主要包括两部分:1、webjars资源,2、自定义的其他html、css、js资源,下面分别介绍两种资源的映射规则。

1)、webjars资源

WebJars是将web前端资源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式对web前端资源进行统一依赖管理,保证这些Web资源版本唯一性。webjars导入对应的xml代码可以在webjars的官网进行复制。

https://www.webjars.org/

SpringBoot对webjars资源的映射规则在WebMvcAutoConfiguration.java包里面,代码部分截图如下所示:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Integer cachePeriod = this.resourceProperties.getCachePeriod();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
        }
        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
        }
    }
}

由上述代码可以看出,所有访问项目根目录下的webjars下的所有资源,都会被映射到classpath:/META-INF/resources/webjars/文件夹下,其中classpath是resources资源文件夹或类的根目录。

而使用maven方式导入的webjars包的静态资源(js、css)会自动放到classpath:/META-INF/resources/webjars/文件夹下,如下所示:

由图可以看出dist中的静态资源文件上层目录为resources/webjars/**

因此在前端引用(此处用的是thymeleaf模板引擎)时可以用如下方式引用:直接从webjars目录开始写即可,上述静态资源映射配置的实际效果即在自己写的资源路径前面加上classpath:/META-INF/resources前缀

<link  th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="external nofollow"  rel="stylesheet">

2)、自己添加的静态资源文件

Spring Boot对自己添加的静态资源文件的映射规则仍然在WebMvcAutoConfiguration.java文件中,实际配置是在ResourcesProperties.java资源文件中CLASSPATH_RESOURCE_LOCATIONS变量。

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

上述配置效果即所有的静态资源的访问除直接访问/webjars/**路径时,会在访问路径前加上上述配置中的任意一个字符串进行查找,直到在相应的文件下找到对应的静态资源。因此在编写SpringBoot应用时一般可以将静态资源放置在resources资源目录下的static或者public文件夹下,如下图所示:

如上图若想访问layui.js可以如下引用静态资源:

<script  th:src="@{/layui/layui.js}"></script>

上述引用之后,SpringBoot会去CLASSPATH_RESOURCE_LOCATIONS变量指定的路径下找layui/layui.js直到找到该文件位置。

CLASSPATH_RESOURCE_LOCATIONS的值可以直接在SpringBoot的配置文件application.properties或yml文件中进行修改。

Thymeleaf模板引擎的映射规则

Thymeleaf模板引擎的映射规则如下所示

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";

上述代码的实际效果是在使用模板引擎是会将请求路径字符串的前面加上classpath:/templates/,后面加上html进行资源请求。因此一般将需要模板引擎进行渲染的html界面放在resources路径下的templates文件夹下,并且在请求的路径字符串中不需要加html后缀。

一个简单的例子如下所示:

    @RequestMapping("/success")
    public String success(Map<String,Object> map){
//        map=new HashMap<>();  这个地方不能再new了
        map.put("hello","hello");
        return "success";
    }

上述代码返回所渲染的html界面即位于resources/templates文件夹下的success.html界面。该默认设置页可以直接在配置文件中通过spring.thymeleaf选项进行修改。

SpringBoot对静态资源的映射规则源码学习笔记

WebMvcAuotConfiguration:

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			//所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
			//webjars:以jar包的方式引入静态资源;
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			//"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			//静态资源文件夹映射
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

resourceProperties

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

getStaticPathPattern():

		源码:
		private String staticPathPattern = "/**";
		public String getStaticPathPattern() {
			return this.staticPathPattern;
		}

getStaticLocations()

			源码:
			private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
			private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
			public String[] getStaticLocations() {
				return this.staticLocations;
			}

//配置欢迎页映射

		@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(
				ResourceProperties resourceProperties) {
				//静态资源文件夹下的所有index.html页面;被"/**"映射;
			return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
		}
		private Optional<Resource> getWelcomePage() {
			String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
			return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
		}
		private Resource getIndexHtml(String location) {
			return this.resourceLoader.getResource(location + "index.html");
		}

getStaticPathPattern()

   源码:
   private String staticPathPattern = "/**";
   public String getStaticPathPattern() {
    return this.staticPathPattern;
   }

//配置喜欢的图标

  @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;
   }
   @Override
   public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
   }
   @Bean
   public SimpleUrlHandlerMapping faviconHandlerMapping() {
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
    //所有  **/favicon.ico 都是在静态资源文件下找
    mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
    return mapping;
   }
   @Bean
   public ResourceHttpRequestHandler faviconRequestHandler() {
    ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
    requestHandler.setLocations(resolveFaviconLocations());
    return requestHandler;
   }
   private List<Resource> resolveFaviconLocations() {
    String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
    List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
    Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add);
    locations.add(new ClassPathResource("/"));
    return Collections.unmodifiableList(locations);
   }
  }

Thymeleaf使用

 源码:
 //只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
 @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";
 }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot通过源码探究静态资源的映射规则实现

    我们开发一个Spring Boot项目,肯定要导入许多的静态资源,比如css,js等文件 如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面的,对吧!但是我们现在的pom呢,打包方式是为jar的方式,那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的! 1.静态资源映射规则 1.1.第一种映射规则 SpringBoot中,SpringMVC的web配置都在 WebMvcA

  • SpringBoot中的五种对静态资源的映射规则的实现

    SpringBoot中的SpringMVC配置功能都是在WebMvcAutoConfiguration类中,xxxxAutoConfiguration就是帮我们给容器中自动配置组件的:idea全局搜索的快捷键是两次shift,查看webMvcAutoConfiguration 查看webMvc自动配置类 WebMvcAutoConfiguration类的原理以后至少还要稍微掌握,而这里文章只是来看它的具体的关键代码,这里只例举部分关键代码,多了看着也头疼,看不懂没关系哈哈哈可跳过源码阶段,何必徒

  • SpringBoot使用Thymeleaf模板引擎访问静态html的过程

    最近要做一个java web项目,因为页面不是很多,所以就没有前后端分离,前后端写在一起,这时候就用到thymeleaf了,以下是不动脑式的傻瓜教程..... 一:创建spring boot的web项目,过程略: 二:依赖如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <

  • SpringBoot+Thymeleaf静态资源的映射规则说明

    目录 Spring Boot中静态资源的映射规则 Thymeleaf模板引擎的映射规则 SpringBoot对静态资源的映射规则源码学习笔记 Spring Boot中静态资源的映射规则 Spring Boot中静态资源主要包括两部分:1.webjars资源,2.自定义的其他html.css.js资源,下面分别介绍两种资源的映射规则. 1).webjars资源 WebJars是将web前端资源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式对web前端资源进行统一依赖管理

  • SpringBoot web静态资源映射实现步骤详解

    目录 静态资源映射规则 自定义静态资源映射规则 静态资源映射规则 “/**” 访问当前项目任何资源,全部找静态资源的文件夹进行映射 静态资源的文件夹包括: "classpath:/META-INF/resources/","classpath:/resources/","classpath:/static/", "classpath:/public/" 静态资源路径下的文件,可以通过地址栏直接访问. 例如:我们在在static

  • 使用springboot对外部静态资源文件的处理操作

    目录 springboot对外部静态资源文件的处理 1.存方面倒还简单,这里贴上一个获取微信临时素材并保存的方法 2.取,由于对springboot不熟悉,所以在这上面踩了坑 主要使用到这2个配置 之后,访问文件一直404 SpringBoot2.x静态资源访问 问题 代码 原理 springboot对外部静态资源文件的处理 springboot对外部资源文件的处理主要分为2部分,存和取,通过查看官方文件和看博客踩了坑之后终于搞定了,特此记录. 1.存方面倒还简单,这里贴上一个获取微信临时素材并

  • springboot访问静态资源遇到的坑及解决

    目录 访问静态资源遇到的坑及解决 直接访问静态资源的问题 SpringBoot 默认静态资源访问配置 引入shiro 或 security后的拦截过滤 访问静态资源遇到的坑及解决 开始是以这种结构进行的,结果页面上一篇红,访问的页面是这样的 最终找出来问题,虽然每次调整路径都不对,最终查看多种方法可以看到了: 增加: package com.example.demo.config; import org.springframework.stereotype.Component; import o

  • 在SpringBoot中静态资源访问方法

    一.概述 springboot 默认静态资源访问的路径为:/static 或 /public 或 /resources 或 /META-INF/resources 这样的地址都必须定义在src/main/resources目录文件中,这样可以达到在项目启动时候可以自动加载为项目静态地址目录到classpath下 ,静态访问地址其实是使用 ResourceHttpRequestHandler 核心处理器加载到WebMvcConfigurerAdapter进行对addResourceHandlers

  • IDEA配置静态资源热加载操作(Springboot修改静态资源不重启)

    第一步: 修改file->settings->compiler->build project automatically 第二步: 按ctrl+shift+a,搜索Registry双击进去,点击面板搜索running,勾选下面的值: 代码的热加载可以使用spring-boot-devtools,百度下就有很多,个人感觉不好用,修改代码需要重启项目,很烦,非常鸡肋,所以我不用,哈哈哈- 补充知识:idea实现修改html等springboot下static目录静态资源重新加载 对于前后端不

  • springboot操作静态资源文件的方法

    默认静态资源供 SpringBoot有几个默认的静态资源目录,当然也可配置,默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources),自定义配置方式如下: spring.mvc.static-path-pattern=/** # Path pattern used for static resources. 前端如果需要访问默认的静态资源,下面有点要注意,考虑下面的目录结构: └─resources │ application.ym

  • SpringBoot访问静态资源的配置及顺序说明

    目录 访问静态资源的配置及顺序 1. SpringBoot的默认配置 2. 测试 3.配置 静态资源的配置心得 举例 访问静态资源的配置及顺序 今天在玩SpringBoot的demo的时候,放了张图片在resources目录下,启动区访问的时候,突然好奇是识别哪些文件夹来展示静态资源的, 为什么有时候放的文件夹不能显示,有的却可以. 1. SpringBoot的默认配置 首先我们打开WebMvcAutoConfiguration类, 因为是静态资源的位置, 所以搜索location,找到这一行代

随机推荐