SpringBoot2.0学习笔记:(五) Spring Boot的静态资源映射

一、静态资源的加载

Spring Boot在引入了Web模块后,就会在启动的时候自动加载与Web有关的配置,所有的配置内容可在

org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration中查看。下面要说的是有关静态资源加载的逻辑。首先看一下这个类
org.springframework.boot.autoconfigure.web.ResourceProperties

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

可以看到这个类是在加载配置文件中有关静态资源的参数,比如缓存时间等。参数前缀是spring.resources

WebMvcAutoConfiguration这个类中,可以找到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));
    }
}
webjars 方式

在其中可以看到,所有包含有/webjars/**的访问路径若没有处理器处理的话都会去classpath:/META-INF/resources/webjars/这个目录下寻找资源。

Webjars官网。

WebJars是将Web前端js和CSS等资源打包成Java的Jar包,这样在Web开发中我们可以借助Maven对这些依赖库进行管理,保证这些Web资源版本唯一性,比如jQuery、Bootstrap等。

这里写图片描述

我们在项目的pom文件引入jquery.jar:

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

可以展开看一下jquery-3.3.1.jar的资源结构:

这里写图片描述

可以看到,所有的资源都在classpath:/META-INF/resources/webjars/这个目录下。我们启动tomcat访问一下

localhost:8080/webjars/jquery/3.3.1/jquery.js看看能否访问的到!

这里写图片描述

很顺利的访问出来了,说明上面说的所有包含有/webjars/**的访问路径都会去classpath:/META-INF/resources/webjars/这个目录下寻找资源是没错的。

“/**”访问任何资源

接着看一下这个方法的后半部分的代码:

String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
    customizeResourceHandlerRegistration(
        registry.addResourceHandler(staticPathPattern)
        .addResourceLocations(getResourceLocations(
            this.resourceProperties.getStaticLocations()))
        .setCachePeriod(getSeconds(cachePeriod))
        .setCacheControl(cacheControl));
}

String staticPathPattern = this.mvcProperties.getStaticPathPattern();这段代码得到的是"/**"这个字符串,也就是说,你访问的任何路径若是没有处理器来处理的话 ,默认会去这里来找资源:this.resourceProperties.getStaticLocations(),即:

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

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/"

我们可以尝试在项目类路径下分别建立这些文件夹,并放入一些静态资源以作访问:

这里写图片描述

在浏览器中依次访问:http://localhost:8080/111.png,确实是可以访问的到的。

二、欢迎页的加载

WebMvcAutoConfiguration这个类中,可以找到welcomePageHandlerMapping这个欢迎页映射方法:

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
    ApplicationContext applicationContext) {
    return new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext),
        applicationContext, getWelcomePage(),
        this.mvcProperties.getStaticPathPattern());
}

static String[] getResourceLocations(String[] staticLocations) {
    String[] locations = new String[staticLocations.length
                                    + SERVLET_LOCATIONS.length];
    System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
    System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length,
                     SERVLET_LOCATIONS.length);
    return locations;
}

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

首先看一下getWelcomePage()这个方法,其逻辑就是循环各个静态资源路径,在其后匹配上index.html,然后首先在哪个静态资源路径下找到了index.html就将此index.html返回。

我们可以在classpath:/static/这个目录下新建一个index.html文件,然后直接访问localhost:8080,可以看到定位到了index.html文件。

三、应用图标的加载 favicon.ico

WebMvcAutoConfiguration这个类中,可以找到FaviconConfiguration这个图标配置的内部类:

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

}

逻辑和欢迎页差不多,只要你将你的图标置于静态资源文件夹中,就会将你自己的favicon.ico这个图标文件作为应用程序的图标。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 尚硅谷SpringBoot 2.0笔记: 1. 基于Java 8,支持Java 11 2. 内嵌Tomcat改为内嵌Jetty 3. 增强了对Spring5.0的支持 4. 增加了对Spring Security 5.0的支持 5. 提供了对Spring Data JPA的增强 6. 增加了对Spring WebFlux的支持 7. 支持Reactive编程 8. 支持Micrometer度量框架 9. 支持Spring Boot Actuator更新 10. 提供了更好的错误处理和调试支持。 ### 回答2: 尚硅谷的Spring Boot 2.0笔记是一份非常系统、详细的资料,包含了Spring Boot 2.0的核心内容及其应用,几乎覆盖了Spring Boot开发的所有方面。 首先,笔记中对于Spring Boot 2.0的基础知识和核心概念进行了详细的介绍,包括Spring Boot的起源、特点和优势,以及基于Spring Boot的开发模式和框架等。此外,笔记还对于Spring Boot 2.0的Maven依赖、配置文件和常用注解进行了讲解,让读者能够轻松上手开发、调试和测试Spring Boot应用程序。 其次,笔记中涵盖了Spring Boot的各种高级特性和应用场景,例如使用Spring Boot开发Web应用、构建RESTful API、使用Spring Boot实现事务控制和数据访问等。此外,笔记中还介绍了Spring Boot在微服务开发中的应用,包括使用Spring Cloud构建分布式架构、服务发现和注册、配置中心和熔断器等。 另外,笔记中还包含了大量的代码案例和实战演练,让读者能够深入理解Spring Boot的使用和开发技巧。同时,笔记还提供了一些最佳实践和调优技巧,让读者能够更加高效地开发和优化Spring Boot应用程序。 总之,尚硅谷Spring Boot 2.0笔记是一份非常有价值的资料,适合于所有对于Spring Boot开发感兴趣的人士。无论是初学者还是有经验的开发人员,都可以从中获取到大量的知识和实践经验,提高自己的技能水平和项目开发能力。 ### 回答3: 尚硅谷springboot2.0笔记是一份非常实用和全面的学习指导材料。它囊括了springboot2.0的各方面知识点,从基础到高级,从搭建环境到实际应用,都有详细而清晰的介绍和实例。 在学习springboot2.0之前,我们先了解一下什么是springbootSpring BootSpring家族的一个全新项目,它通过提供各种有用的开箱即用的功能来简化Spring应用程序的开发和部署。因此,Spring Boot能够大大简化Web应用程序的开发,无需像以前那样手动配置各种组件,同时它的错误处理和日志记录等特性也非常实用。 尚硅谷springboot2.0笔记的内容非常丰富,其中包括了Spring Boot的介绍、搭建环境、基础用法、自动配置原理、Web开发、数据访问、消息服务、安全与监控等。除此之外,该笔记还详细讲解了常见的一些中间件的使用,比如Redis,RabbitMQ等。 与其他的学习资料相比,尚硅谷springboot2.0笔记的特点在于其结合了理论和实践,讲解清晰而且非常易于理解,并且笔记中的实例也非常实用,可以让读者更加深入的理解Spring Boot的各个方面。 总之,如果你想学习Spring Boot 2.0,尚硅谷springboot2.0笔记无疑是一个非常不错的选择。在学习的过程中,要不断动手实践,加深自己的理解,这样才能真正掌握这门技术。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值