springboot(5)——处理静态资源

问题1:静态资源的导入

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
			if (!this.resourceProperties.isAddMappings()) {
    
     // 使用默认静态资源处理--->return
				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)
						.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern(); // 获得静态资源的路劲
			if (!registry.hasMappingForPattern(staticPathPattern)) {
    
    
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
						.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
			}
		}

那我们如何自定义这个静态资源?
方式一我们平时也不会这么使用
首先找到

// Defined as a nested config to ensure WebMvcConfigurer is not read when not
	// on the classpath
	@SuppressWarnings("deprecation")
	@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({
    
     WebMvcProperties.class,
			org.springframework.boot.autoconfigure.web.ResourceProperties.class, WebProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
    
    

中的WebMvcProperties.class
在这里插入图片描述

	if (!registry.hasMappingForPattern("/webjars/**")) {
    
    
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
						.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
			}

这个webjars是静态资源存储的路径。什么是webjars?
在这里插入图片描述
我们打开网址https://www.webjars.org/ 找到jquery的maven的坐标
在这里插入图片描述
添加到pom.xml
引入之后的地址对应
在这里插入图片描述
在这里插入图片描述
方式二
在这里插入图片描述
在这里插入图片描述
注意这个classpath是resources路径,这个/**的根路径就是localhost:8080/也就是resources/static 、 resources/public 等,如例
首先配置application.yaml
在这里插入图片描述
然后
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zs18753479279/article/details/112505496
今日推荐