对静态资源进行相关操作:
spring:
mvc:
static-path-pattern: /jt/** #为静态资源设置前缀
web:
resources:
static-locations: [classpath:/static/]
#设置静态资源存放的目录,注意classpath后面不能有空格,且默认的存放位置也会不管用
源码解析
/*静态资源信息处理规则:
当我们的add-mapings设置为false时,会进入第一个if语句:直接跳出方法,下面的静态资源规则就作废了,能达到禁用的目的
但add-mapings默认为true时,就会执行下列的静态资源处理规则: 默认就是下面的规则*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
ServletContext servletContext = getServletContext();
//我们导入的jar包的文件就可以从下面路径找到
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
//将我们本身的资源写到里面
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
//这个方法就里面就指定了我们的固定的静态资源地址
// this.resourceProperties.getStaticLocations() 会先拿到我们设置的静态资源地址路径
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (servletContext != null) {
//添加我们设置的资源地址
registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
}
});
}
private void addResourceHandler(ResourceHandlerRegistry registry, String pattern,
Consumer<ResourceHandlerRegistration> customizer) {
if (registry.hasMappingForPattern(pattern)) {
return;
}
ResourceHandlerRegistration registration = registry.addResourceHandler(pattern);
//调用此方法回将我们设置的静态资源路径读入到registration
customizer.accept(registration);
registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod()));
registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
customizeResourceHandlerRegistration(registration);
}