SpringBoot Thymeleaf静态资源映射 SpringBoot+Thymeleaf静态资源的映射规则说明
qq_39602928 人气:0Spring Boot中静态资源的映射规则
Spring Boot中静态资源主要包括两部分:1、webjars资源,2、自定义的其他html、css、js资源,下面分别介绍两种资源的映射规则。
1)、webjars资源
WebJars是将web前端资源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式对web前端资源进行统一依赖管理,保证这些Web资源版本唯一性。webjars导入对应的xml代码可以在webjars的官网进行复制。
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"; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容