thymeleaf配置html资源路径,SpringBoot+thymeleaf+静态资源引入

本文介绍了SpringBoot中Thymeleaf的配置以及如何处理静态资源,包括默认的静态资源映射规则,如classpath:/META-INF/resources/、classpath:/resources/、classpath:/static/、classpath:/public/以及/(项目根路径)。优先级从上到下,如果多个目录存在相同资源,将优先加载优先级高的目录中的资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、静态资源的映射规则

1.对哪些目录映射?

classpath:/META-INF/resources/

classpath:/resources/

classpath:/static/

classpath:/public/

/:当前项目的根路径

意思是:我们在上面的五个目录下放静态资源文件(比如:jq.js等),可以直接访问(类似以前web项目的webapp下,放到其他目录无法被访问。

2.为什是这几个目录呢?

2.1看源码就知道

SpringBoot自动配置的WebMvcAutoConfirarution.java类:

@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();

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 {

//我们可以看到静态资源的映射路径

private static final String[] CLASSPATH_RESOURCE_LOCATIONS={

"classpath:/META-INF/resources/", "classpath:/resources/",

"classpath:/static/", "classpath:/public/" };

...

}

总的来说:

WebMvcAutoConfiguration类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。

classpath:/META-INF/resources/

classpath:/resources/

classpath:/static/

classpath:/public/

/:当前项目的根路径

优先级从上到下。

所以,如果static里面有个index.html,public下面也有个index.html,则优先会加载static下面的index.html,因为优先级!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值