SpringBoot - 静态资源映射处理


【1】静态资源文件映射规则

同样查看WebMVCAutoConfiguration源码如下:

        @Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");return;}Integer cachePeriod = this.resourceProperties.getCachePeriod();if (!registry.hasMappingForPattern("/webjars/**")) {customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(cachePeriod));}// 对静态资源文件映射支持String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));}}

具体支持代码如下:

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

第一步拿到staticPathPattern;

    /*** Path pattern used for static resources.*/private String staticPathPattern = "/**";

第二步如果资源请求没有对应映射,就添加资源处理器及资源找寻位置并设置缓存

if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));}

其中 staticLocations在ResourceProperties类中,源码如下:

/*** Properties used to configure resource handling.** @author Phillip Webb* @author Brian Clozel* @author Dave Syer* @author Venil Noronha* @since 1.1.0*/
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/", "classpath:/public/" };private static final String[] RESOURCE_LOCATIONS;static {RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length+ SERVLET_RESOURCE_LOCATIONS.length];System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,SERVLET_RESOURCE_LOCATIONS.length);System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);}/*** Locations of static resources. Defaults to classpath:[/META-INF/resources/,* /resources/, /static/, /public/] plus context:/ (the root of the servlet context).*/private String[] staticLocations = RESOURCE_LOCATIONS;

即:"/**"访问当前项目的任何资源,只要没有匹配的处理映射,则都去静态资源的文件夹找映射

"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径


如下图,访问static/asserts/img/bootstrap-solid.svg:

URL : http://localhost:8083/asserts/img/bootstrap-solid.svg;

这里注意URL上面不要添加静态资源文件夹(路径)的名字,如static、public等等。


【2】默认欢迎页的映射

代码如下:

        @Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),this.mvcProperties.getStaticPathPattern());}

注册了WelcomePageHandlerMappingBean来处理项目的默认欢迎页面,构造器有两个参数,第一个是项目中存在的欢迎页资源,第二个是静态资源路径映射规则。


① 获取欢迎页资源

其中跟踪resourceProperties.getWelcomePage()源码:

    public Resource getWelcomePage() {for (String location : getStaticWelcomePageLocations()) {Resource resource = this.resourceLoader.getResource(location);try {if (resource.exists()) {resource.getURL();return resource;}}catch (Exception ex) {// Ignore}}return null;}

即找到存在的欢迎页的资源,继续跟getStaticWelcomePageLocations()源码:

private String[] getStaticWelcomePageLocations() {String[] result = new String[this.staticLocations.length];for (int i = 0; i < result.length; i++) {String location = this.staticLocations[i];if (!location.endsWith("/")) {location = location + "/";}result[i] = location + "index.html";}return result;}

即 欢迎页的位置为第【1】部分中静态资源文件路径下的index.html。

如下所示:

"classpath:/META‐INF/resources/index.html",
"classpath:/resources/index.html",
"classpath:/static/index.html",
"classpath:/public/index.html"
"/":/index.html

② 静态路径映射规则

/*** Path pattern used for static resources.*/private String staticPathPattern = "/**";

③ WelcomePageHandlerMapping类

static final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class);private WelcomePageHandlerMapping(Resource welcomePage,String staticPathPattern) {if (welcomePage != null && "/**".equals(staticPathPattern)) {logger.info("Adding welcome page: " + welcomePage);ParameterizableViewController controller = new ParameterizableViewController();controller.setViewName("forward:index.html");setRootHandler(controller);setOrder(0);}}@Overridepublic Object getHandlerInternal(HttpServletRequest request) throws Exception {for (MediaType mediaType : getAcceptedMediaTypes(request)) {if (mediaType.includes(MediaType.TEXT_HTML)) {return super.getHandlerInternal(request);}}return null;}private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) {String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);return MediaType.parseMediaTypes(StringUtils.hasText(acceptHeader) ? acceptHeader : "*/*");}}

总结:项目访问时,请求如http://localhost:8083/,则SpringBoot会从静态资源文件路径下找index.html,如果存在一个这样的资源,就转发请求到该页面。


【3】项目浏览器图标的映射

SpringBoot同样对项目浏览器图标请求映射做了默认配置。浏览器图片即项目访问时,浏览器页面上呈现的图标,如CSDN图标如下


代码如下:

        @Configuration@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)public static class FaviconConfiguration {private final ResourceProperties resourceProperties;public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;}@Beanpublic SimpleUrlHandlerMapping faviconHandlerMapping() {SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",faviconRequestHandler()));return mapping;}@Beanpublic ResourceHttpRequestHandler faviconRequestHandler() {ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();requestHandler.setLocations(this.resourceProperties.getFaviconLocations());return requestHandler;}}

跟踪源码this.resourceProperties.getFaviconLocations()如下:

List<Resource> getFaviconLocations() {List<Resource> locations = new ArrayList<Resource>(this.staticLocations.length + 1);if (this.resourceLoader != null) {for (String location : this.staticLocations) {locations.add(this.resourceLoader.getResource(location));}}locations.add(new ClassPathResource("/"));return Collections.unmodifiableList(locations);}

即在静态资源文件下找所有的favicon.ico !

SpringBoot - 静态资源映射处理相关推荐

  1. SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url

    场景 前端调用上传照片的功能,将某照片上传到服务器上某磁盘路径下,然后将通过静态资源映射,将在服务器上 访问的地址存储到数据库中,这样在需要获取这种照片的时候就能通过服务器上的url来获取和显示这张照 ...

  2. 基于Springboot外卖系统03:pom.xml导入依赖+数据库配置文件+Boot启动类+静态资源映射

    1).在pom.xml中导入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns= ...

  3. 第14章 SpringBoot静态资源处理

    第14章 SpringBoot静态资源处理 14.1 WebMvcAutoConfiguration的默认配置 14.2 自定义静态资源映射 14.3 前端资源的引用方法

  4. Spring Boot 静态资源映射与上传文件路由配置

    默认静态资源映射目录 默认映射路径 在平常的 web 开发中,避免不了需要访问静态资源,如常规的样式,JS,图片,上传文件等;Spring Boot 默认配置对静态资源映射提供了如下路径的映射 /st ...

  5. springboot-2.2.5中自定义拦截器、静态资源映射、视图控制器和其他功能

    在spring-boot-2.2.5中对MVC自动配置类进行的更改,之前的WebMvcConfigurerAdapter类声明为过时的,现在进行自定义扩展需要实现WebMvcConfigurer类重写 ...

  6. Spring Boot静态资源映射

    在 Web 应用中会涉及到大量的静态资源,例如 JS.CSS 和 HTML 等.我们知道,Spring MVC 导入静态资源文件时,需要配置静态资源的映射:但在 SpringBoot 中则不再需要进行 ...

  7. Spring boot修改静态资源映射

    staticLocations 静态资源映射路径 可以配置staticLocations 修改静态资源映射路径 配置信息 spring.resources.static-locations=class ...

  8. Spring boot的静态资源映射

    静态资源映射 创建Web工程 WebMvcAutoConfiguration Ctrl+Shift+R 搜索addResourceHandlers resourceProperties 可以设置和静态 ...

  9. Nginx搭建静态资源映射实现远程访问服务器上的图片资源

    场景 需求是从A系统中预览B系统中抓拍的照片. B系统在另一条服务器上,照片的路径是绝对路径 类似D:\aa\badao.jpg这样的图片路径. 在A系统中查询B系统的数据库能获取图片的路径. 需要将 ...

最新文章

  1. Windows XP源代码泄露,外媒从中发现隐藏Mac主题
  2. 移动设备感染率及物联网设备安全漏洞数量创下历史新高
  3. 关闭Outlook自动完成功能
  4. MooTools Class 使用、继承详解
  5. 判断是否为微信环境下打开的网页
  6. 16.算法调用优先于手写的循环
  7. HDU - 5875 Function(单调栈)
  8. CSDN-Markdown编辑器使用小技巧
  9. js百度地图android定位不准,百度地图js定位不准
  10. 盘点2012中国承载网十大事件(转)
  11. 猎豹浏览器_金山猎豹浏览器_官方正式版下载_首款双核安全浏览器
  12. 基于Pytorch实现CNN卷积神经网络-Mnist数据集
  13. dev grdicontrol 根据条件改变行颜色,字体颜色等
  14. python微博接口_Python使用新浪微博API发送微博的例子
  15. PRD文档写作详细说明(希望对大家有用)
  16. python计算圆锥体积和表面积_圆锥体积公式和表面积
  17. 汉诺塔(hanoi)、双色汉诺塔(分离型)、三色汉诺塔
  18. elasticsearch for windows
  19. 【转载】因为专注,所以专业
  20. POJ - 1723 Soldiers 士兵站队 排序+中位数

热门文章

  1. Mind+实时模式智能问答机器人
  2. 5000字“肝”了这篇IP协议
  3. 【STM32】各类通信接口及协议简识(IIC、SPI、RS232、RS485、CAN、USB)
  4. STC51-A/D和D/A
  5. linux路由内核实现分析(四)---路由缓存机制(3)
  6. struct sk_buff与struct socket及struct sock 结构体分析
  7. CUDA GPU编程
  8. 【JUC】第六章 Fork/Join 框架、CompletableFuture
  9. jdk1.8新特性的应用-Stream Api
  10. 召回率和精确率(recall and precision)