文章目录
静态资源访问
静态资源目录、静态资源访问前缀
默认情况下,Spring Boot从类路径中名为/static、/public、/resources、/META-INF/resources
的目录或根目录提供静态内容。
访问 : 当前项目根路径/ + 静态资源名
原理: 资源映射到/**
,但是您可以使用spring.mvc.static-path-pattern
属性对其进行调整。
请求进来,先去找Controller
看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404
页面。
改变默认的静态资源路径
spring:
mvc:
# 静态资源访问前缀
static-path-pattern: /static/**
resources:
# 静态资源路径
static-locations: classpath:/abc/
欢迎页支持
静态资源路径下创建 index.html
- 可以配置静态资源路径
- 但是不可以配置静态资源的访问前缀。否则导致
index.html
不能被默认访问
spring:
# mvc:
# # 静态资源访问前缀
# static-path-pattern: /static/**
resources:
# 静态资源路径
static-locations: classpath:/abc/
也可以在 templates
目录下创建 index.html
,但是需要依赖 thymeleaf
。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
自定义 Favicon
favicon.ico
放在静态资源目录下即可。
但是如果配置了静态资源的访问前缀会失效。
静态资源配置原理
SpringBoot启动默认加载 xxxAutoConfiguration
类(自动配置类)
SpringMVC功能的自动配置类 WebMvcAutoConfiguration
。
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration { }
给容器中配了什么,配置文件的相关属性和xxx进行了绑定。WebMvcProperties==spring.mvc
、ResourceProperties==spring.resources
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer { }
资源处理的默认规则。
@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));
}
}
静态资源路径配置。
@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/" };
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
欢迎页的处理规则
HandlerMapping:处理器映射。保存了每一个Handler能处理哪些请求。
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
//从这里可以看出,要用欢迎页功能,必须是/**
logger.info("Adding welcome page: " + welcomePage.get());
setRootViewName("forward:index.html");
}
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}
自定义配置静态资源映射
通过 application.properties 配置文件
# 定义资源位置
spring.resources.static-locations=classpath:/static
# 定义请求 URL 规则
spring.mvc.static-path-pattern=/api/*
通过 Java 代码
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/demo/");
}
}
总结
SpringBoot 默认使用了 Thymeleaf 作为模板引擎,会将html静态资源放在 resources/templates
目录下,注意,templates
目录并不是静态资源目录,它是一个放页面模板的位置(Thymeleaf 模板虽然后缀为 .html,其实并不是静态资源)。