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("/webjarsfavicon.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";
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。