静态资源配置原理

SpringMVC功能的自动配置类 WebMvcAutoConfiguration

一、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 {}

在WebMvcAutoConfiguration里配置了WebMvcAutoConfigurationAdapter

@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}

因此会导入EnableWebMvcConfiguration配置类

WebMvcProperties里绑定spring.mvc开头的配置

ResourceProperties绑定spring.resources开头的配置

WebMvcAutoConfigurationAdapter类有一个构造函数

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
      ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
      ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
      ObjectProvider<DispatcherServletPath> dispatcherServletPath,
      ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
   //获取和spring.resources绑定的所有的值的对象
   this.resourceProperties = resourceProperties;
   //获取和spring.mvc绑定的所有的值的对象
   this.mvcProperties = mvcProperties;
   //Spring的beanFactory
   this.beanFactory = beanFactory;
   //找到所有的HttpMessageConverters
   this.messageConvertersProvider = messageConvertersProvider;
   // 找到 资源处理器的自定义器
   this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
   //给应用注册Servlet、Filter....
   this.dispatcherServletPath = dispatcherServletPath;
   this.servletRegistrations = servletRegistrations;
}

二、静态资源处理的默认规则设置

在WebMvcAutoConfigurationAdapter里addResourceHandlers方法是用于处理资源的默认规则

@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));
   }
}

1、this.resourceProperties.isAddMappings() 是控制默认资源管理是否开启

spring.resources.add-mappings来控制,默认值为true。

2、配置webjar默认资源
自动映射 /webjars/**

webjars在如下网址下下载WebJars - Web Libraries in Jarshttps://www.webjars.org/

以jquery为例

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

3、静态资源默认设置

(1)静态资源前缀设置

spring.mvc.static-path-pattern默认值为/**

(2)静态资源默认所在目录

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
      "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

默认资源访问 : 当前项目根路径/ + 静态资源名

4、案例

spring:
  mvc:
    static-path-pattern: /res/**

resources:
  static-locations: [classpath:/templates/]

(当前项目 + static-path-pattern + 静态资源名) 会去默认静态资源文件夹下找

三、欢迎页的处理规则设置

在WebMvcAutoConfiguration里WelcomePageHandlerMapping配置来提供欢迎页配置

@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");
   }
}

1、要用欢迎页功能,必须是/**

2、如果不是/**前缀则调用Controller里的/index来显示欢迎页

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值