Spring Boot深度课程系列

峰哥说技术—2020庚子年重磅推出、战胜病毒、我们在行动

10  峰哥说技术:Spring Boot静态资源处理

今天我们聊聊关于 Spring Boot 中关于静态资源的问题,这样,峰哥还是带着大家回顾一下SSM中是怎么处理静资源的。我们得先回到 SSM 环境中,一般来说,我们可以通过 <mvc:resources/> 节点来配置不拦截静态资源,如下所示

<mvc:resources mapping="/js/**" location="/js/"/>

<mvc:resources mapping="/css/**" location="/css/"/>

<mvc:resources mapping="/html/**" location="/html/"/>

由于这是一种Ant风格的路径匹配符, /** 表示可以匹配任意层级的路径,因此上面的代码也可以像下面这样简写:

<mvc:resources mapping="/**" location="/"/>

Spring boot对于Spring MVC的自动化配置都在WebMvcAutoConfiguration,因此对于静态资源的过滤策略我们只要在这里看一下应该就一目了然了。当我们打开改配置类后发现该类有一个静态的内部类WebMvcAutoConfigurationAdapter。

@Configuration(
    proxyBeanMethods = false
)
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
    private static final Log logger = LogFactory.getLog(WebMvcConfigurer.class);
    private final ResourceProperties resourceProperties;
    private final WebMvcProperties mvcProperties;
    private final ListableBeanFactory beanFactory;
    private final ObjectProvider<HttpMessageConverters> messageConvertersProvider;
    final WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider) {
        this.resourceProperties = resourceProperties;
        this.mvcProperties = mvcProperties;
        this.beanFactory = beanFactory;
        this.messageConvertersProvider = messageConvertersProvider;
        this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
    }

//其他省略...

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

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

//其他省略....
}

}

在这里重点考察staticPathPattern和resouruceProperties,这里肯定需要到WebMvcProperties ResourceProperties 去查看。

public class WebMvcProperties {
    private Format messageCodesResolverFormat;
    private Locale locale;
    private WebMvcProperties.LocaleResolver localeResolver;
    private String dateFormat;
    private boolean dispatchTraceRequest;
    private boolean dispatchOptionsRequest;
    private boolean ignoreDefaultModelOnRedirect;
    private boolean publishRequestHandledEvents;
    private boolean throwExceptionIfNoHandlerFound;
    private boolean logResolvedException;
    private String staticPathPattern;
    private final WebMvcProperties.Async async;
    private final WebMvcProperties.Servlet servlet;
    private final WebMvcProperties.View view;
    private final WebMvcProperties.Contentnegotiation contentnegotiation;
    private final WebMvcProperties.Pathmatch pathmatch;

public WebMvcProperties() {
        this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER;
        this.dispatchTraceRequest = false;
        this.dispatchOptionsRequest = true;
        this.ignoreDefaultModelOnRedirect = true;
        this.publishRequestHandledEvents = true;
        this.throwExceptionIfNoHandlerFound = false;
        this.logResolvedException = false;
        this.staticPathPattern = "/**";
        this.async = new WebMvcProperties.Async();
        this.servlet = new WebMvcProperties.Servlet();
        this.view = new WebMvcProperties.View();
        this.contentnegotiation = new WebMvcProperties.Contentnegotiation();
        this.pathmatch = new WebMvcProperties.Pathmatch();
    }

//其他省略....

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;
    private boolean addMappings;
    private final ResourceProperties.Chain chain;
    private final ResourceProperties.Cache cache;

//其他省略....

}

然后再看标红的地方,在加上WebMvcAutoConfiguration中的SERVLET_LOCATIONS = new String[]{"/"};我们需要的答案就呼之欲出了。最后的结论如下:

Spring Boot 中支持5个静态资源位置,分别是:"classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/", "classpath:/public/",然后在getResourceLocations方法中,又添加了“/”,因此这里返回值一共有5个。其中,/表示webapp目录,即webapp中的静态文件也可以直接访问。静态资源的匹配路径按照定义路径优先级依次降低。我们可以通过一个案例来说明这里的优先级。

案例:分别在静态资源的5个位置放置名称相同但是内容不同的图片,启动后访问,依次删除,验证规则。

步骤:

1)创建Spring boot工程,按下图构建。

特别说明:pom.xml中添加web依赖,除此之外,不需要任何的配置。配置大家已经很熟悉,这里省略。

2)补全工程文件夹,如下图所示。并添加图片到文件夹中。

3)启动项目,任何进行访问。依次删除进行测试。省略过程,大家自己可以试试。

以上所讲的是系统的默认配置,如果我们想自己进行自定义该怎么进行呢?其实也非常简单。有两种方式可以进行,一种是在application.properties中进行配置。另外一种是配置Java类,也可以。下面分别进行举例说明。

1)在application.properties中进行自定义的配置静态资源

spring.resources.static-locations=classpath:/
spring.mvc.static-path-pattern=/**

第一行配置表示定义资源位置,第二行配置表示定义请求 URL 规则。以上文的配置为例,如果我们这样定义了,表示可以将静态资源放在 resources目录下的任意地方,我们访问的时候当然也需要写完整的路径,例如在resources/static目录下有一张名为1.png 的图片,那么访问路径就是 http://localhost:8080/static/1.png ,注意此时的static不能省略。

2)通过Java配置类自定义静态资源

package com.java.chapter02jsp.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
 registry.addResourceHandler("/**").addResourceLocations("classpath:/aaa");
    }
}

工程截图如下:

在浏览器中输入:http://localhost:8080/aaa/1.jpg。可以看到图片,这里要说明的是必须带上aaa,否则报错,大家需要特别关注。

很多人用了 Thymeleaf 之后,会将静态资源也放在 resources/templates 目录下,注意,templates 目录并不是静态资源目录,它是一个放页面模板的位置(你看到的 Thymeleaf 模板虽然后缀为 .html,其实并不是静态资源)

峰哥说技术:10-Spring Boot静态资源处理的更多相关文章

  1. 峰哥说技术:09-Spring Boot整合JSP视图

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 09  峰哥说技术:Spring Boot整合JSP视图 一般来说我们很少推荐大家在Spring boot ...

  2. 峰哥说技术:08-Spring Boot整合FreeMarker视图

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 08  峰哥说技术:Spring Boot整合FreeMarker视图 前面带着大家整合了Thymelea ...

  3. 峰哥说技术:04-Spring Boot基本配置

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 04 Spring Boot基本配置 1)容器的相关配置 在Spring Boot中可以内置Tomcat. ...

  4. Spring Boot 静态资源处理

    spring Boot 默认的处理方式就已经足够了,默认情况下Spring Boot 使用WebMvcAutoConfiguration中配置的各种属性. 建议使用Spring Boot 默认处理方式 ...

  5. 从零开始的Spring Boot(3、Spring Boot静态资源和文件上传)

    Spring Boot静态资源和文件上传 写在前面 从零开始的Spring Boot(2.在Spring Boot中整合Servlet.Filter.Listener的方式) https://www. ...

  6. Spring Boot静态资源处理

    Spring Boot静态资源处理 8.8 Spring Boot静态资源处理 当使用Spring Boot来开发一个完整的系统时,我们往往需要用到前端页面,这就不可或缺地需要访问到静态资源,比如图片 ...

  7. Spring Boot 静态资源处理(转)

    Spring Boot 静态资源处理 Spring Boot 系列 Spring Boot 入门 Spring Boot 属性配置和使用 Spring Boot 集成MyBatis Spring Bo ...

  8. 峰哥说技术:03-Spring Boot常用注解解读

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 03 Spring Boot常用注解解读 在Spring Boot中使用了大量的注解,我们下面对一些常用的 ...

  9. 峰哥说技术:01-Spring Boot介绍

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 Spring Boot介绍 A.Spring Boot是什么? 由于Spring是一个轻量级的企业开发框架 ...

随机推荐

  1. android版本更新框架、新闻客户端、音乐播放器、自定义View、Github客户端、指南针等源码

    Android精选源码 XUpdate 一个轻量级.高可用性的Android版本更新框架 Android一个可定制的圆形进度条 Android自定义View分享 打钩动画源码 android音乐文件播 ...

  2. UTF虚拟对象

    虚拟对象: 虚拟对象是为了让UFT识别某些不能识别的控件,把这些控件的范围定义为虚拟对象. 新建虚拟对象 管理虚拟对象 创建虚拟对象之后可通过菜单tools-Virutal Objects-Virut ...

  3. 一致性 hash 算法( consistent hashing )及java实现

    consistent hashing 算法早在 1997 年就在论文 Consistent hashing and random trees 中被提出,目前在cache 系统中应用越来越广泛: 1 基 ...

  4. @Value默认值填null

    @Value("${topology.position.spout.maxpending:#{null}}") private Integer spoutMaxPending; @ ...

  5. webStrom 运行React-Native项目

    1.点击“Edit Configurations...” 2.点击“+”选择“npm” 3.“Name”随便输入一个名称,“Command”改为“help”,然后在点击“+”号. 4.选择“Run E ...

  6. WEB前端资源集(二)

    在上一篇为大家整理出了一些资源网站,接下来给大家整理了一些开发中常用的工具. 开发工具篇 开发工具集 Sublime Text 3:SublimeText 3是一个代码编辑器,也是HTML和散文先进的 ...

  7. 吴裕雄--天生自然 R语言开发学习:基本图形(续二)

    #---------------------------------------------------------------# # R in Action (2nd ed): Chapter 6 ...

  8. Ionic3学习笔记(六)存储之使用 SQLite

    本文为原创文章,转载请标明出处 目录 安装 CURD操作 1. 安装 命令行输入 ionic cordova plugin add cordova-sqlite-storage npm install ...

  9. php发送post请求的4种方式

    http://blog.163.com/fan_xy_qingyuan/blog/static/188987748201411943815244/ class Request{ public stat ...

  10. js javascript 获取url,获得当前页面的url,静态html文件js读取url参数

    获得当前页面的url window.location.href 静态html文件js读取url参数 location.search; //获取url中"?"符后的字串 下边为转载的 ...