6.SpringBoot Web开发-webjars&静态资源映射规则(欢迎页和角标favicon.ico替换)

2023-11-02

文章总结:作为一个后端开发,在Springboot中怎样引入需要的js依赖以及常用的静态资源映射呢?SpringBoot已经给做好了自动化配置,使用时只需要按照默认的配置去放相应的文件,就可以快速上手。

1、创建SpringBoot web项目(参考之前文章-使用Spring Initializer快速创建Spring Boot项目)

​ 1)创建SpringBoot 应用,选择需要的模块;

​ 2)SpringBoot 已经默认配置好相应的场景,只需指定少量配置就可以运行;

​ 3)编写业务代码

2、SpringBoot web的自动配置会加载那些配置

xxxxAutoConfiguration:给容器中自动配置组件;xxxxProperties:配置类来封装配置文件的内容;

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration { 
//Web 加载的配置组件
@Deprecated
@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties extends Resources {
// 配置文件可以设置和静态资源有关的参数,缓存时间等

3、SpringBoot对静态资源的映射规则;

​ 1)添加静态资源文件映射 :WebMvcAutoConfiguration 中的addResourceHandlers 方法

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (this.servletContext != null) {
                ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                registration.addResourceLocations(new Resource[]{resource});
            }

        });
    }
}

怎么通过maven配置添加Jquery的依赖?所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源

  • 添加maven依赖(去 https://www.webjars.org/ 官网找到相应的JQuery 相应的配置)
<!--引入jquery-webjar-->在访问的时只需要写webjars下面资源的名称即可
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>
  • 重启项目访问lIP:端口/webjars/jquery/3.3.1/jquery.js 即可

  • “/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找相应映射默认寻找路径如下

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

    IP:端口/abc === 去静态资源文件夹里面找abc

​ 2)配置欢迎页:WebMvcAutoConfiguration 中的addResourceHandlers 方法

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
    return welcomePageHandlerMapping;
    
     private Resource getWelcomePage() {
            String[] var1 = this.resourceProperties.getStaticLocations();
            int var2 = var1.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                String location = var1[var3];
                Resource indexHtml = this.getIndexHtml(location);
                if (indexHtml != null) {
                    return indexHtml;
                }
            }

            ServletContext servletContext = this.getServletContext();
            if (servletContext != null) {
                return this.getIndexHtml((Resource)(new ServletContextResource(servletContext, "/")));
            } else {
                return null;
            }
        }

        private Resource getIndexHtml(String location) {
            return this.getIndexHtml(this.resourceLoader.getResource(location));
        }

        private Resource getIndexHtml(Resource location) {
            try {
                Resource resource = location.createRelative("index.html");
                if (resource.exists() && resource.getURL() != null) {
                    return resource;
                }
            } catch (Exception var3) {
                ;
            }

            return null;
        }

具体的是那个配置页面,可以根据代码可以找到是静态资源文件夹下的所有index.html页面,

访问IP:port/ 就会去静态文件夹下找index.html

  1. 配置角标:所有的 **/favicon.ico 都是在静态资源文件下找(下面的源码Springboot 版本为1.5.3)
//配置喜欢的图标
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {

    private final ResourceProperties resourceProperties;

    public FaviconConfiguration(ResourceProperties resourceProperties) {
        this.resourceProperties = resourceProperties;
    }

    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        //所有  **/favicon.ico 
        mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
                                                   faviconRequestHandler()));
        return mapping;
    }

    @Bean
    public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler
            .setLocations(this.resourceProperties.getFaviconLocations());
        return requestHandler;
    }

}

总结:之前只会从静态文件夹里引入常用的全框架js,通过此篇文章知道了,还可以通过maven引入;想要配置欢迎页和角标都是在默认的静态文件下的index.heml和favicon.ico 。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

6.SpringBoot Web开发-webjars&静态资源映射规则(欢迎页和角标favicon.ico替换) 的相关文章

随机推荐

  • C++14新特性

    C 14 维基百科 C 14是C 的现行标准的非正式名称 正式名称为 International Standard ISO IEC 14882 2014 E Programming Language C C 14旨在作为C 11的一个小扩展
  • oracle的备份与恢复(一)

    author skate time 2010 09 06 oracle的备份与恢复 基于我个人的理解把恢复分为来两大类 1 基于备份的恢复 这种基于备份饿恢复是指通过备份文件 redo archivelog等来实现备份 2 没有备份的恢复
  • HyperLogLog(关于基数统计)

    写在前面 今天在复习Redis的一种在Redis 2 8 9 版本更新的结构的时候 知道了这个数据结构是基于一种优秀的算法HyperLogLog 基数统计算法 简单来说就是统计集合中的元素数量 但是对比set有了很大的优化 就去了解了一下这
  • Lemmings4

    See also Lemmings1 Lemmings2 and Lemmings3 Although Lemmings can walk fall and dig Lemmings aren t invulnerable If a Lem
  • ARouter原理剖析及手动实现

    简介 最近可能入了魔怔 也可能是闲的蛋疼 自己私下学习了ARouter的原理以及一些APT的知识 为了加深对技术的理解 同时也本着热爱开源的精神为大家提供分享 所以就带着大家强行撸码 分析下ARouter路由原理和Android中APT的使
  • U-Boot 启动流程详解

    文章目录 链接脚本 u boot lds 详解 Uboot启动流程 链接脚本 u boot lds 详解 要分析 uboot 的启动流程 首先要找到 入口 找到第一行程序在哪里 程序的链接是由链接脚本来决定的 所以通过链接脚本可以找到程序的
  • linux驱动模块编译Makefile

    该Makefile最好是和hello c同样的路径 obj m hello o 表示编译生成的模块 前缀hello必须和 c文件相同 all make C lib modules shell uname r build M PWD modu
  • /bin/sh: 1: nvcc: not found Makefile:89: recipe for target 'obj/convolutional_kernels.o' failed

    在测试YOLO时出现 nvcc gencode arch compute 30 code sm 30 gencode arch compute 35 code sm 35 gencode arch compute 50 code sm 50
  • 高性能内存分配器 jemalloc 基本原理

    Netty 内存管理的实现并不是一蹴而就的 它也是参考了 jemalloc 内存分配器 今天我们就先介绍 jemalloc 内存分配器的基本原理 为我们后面的课程打好基础 背景知识 jemalloc 是由 Jason Evans 在 Fre
  • [Warning] ‘typedef‘ was ignored in this declaration解决

    首先先展示一下问题是怎么样的 出现了 typedef was ignored in this declaration的问题 下面提供解决方案及原因 原因 在于使用结构体的时候没有使用别名 解决方案 1 去掉typedef 2 在结构体后面加
  • elementui tree怎样设置默认勾选

    在树形菜单数据里面设置一个唯一的字段 这里我的就是id字段 然后设置node key为那个唯一字段 然后用default checked keys绑定一个数组 这个数组里面就是需要勾选的菜单所对应的的id 比如我这里的是9 这样运行之后菜单
  • echarts使用结合时间轴timeline动态刷新案例

    1 echarts简介 ECharts 一个使用 JavaScript 实现的开源可视化库 可以流畅的运行在 PC 和移动设备上 兼容当前绝大部分浏览器 IE8 9 10 11 Chrome Firefox Safari等 底层依赖轻量级的
  • unity的UGUI的mask(遮罩)的使用

    之前我写过一篇博客关于UGUI的优化 其中提到了Mask的使用会增加性能的消耗 但是在一些情况下 使用这个会有奇效 比如小地图 Minimap 的开发 这篇博客介绍一下UGUI中的Mask的使用方法 很简单的 首先创建一个 Image 给他
  • 【PHP发送邮件】PHP实现发送邮件

    PHP发送邮件 Thinkphp直接使用 其他框架修改使用 1 安装 composer require phpmailer phpmailer 2 填写配置表 配置文件mail php
  • MQTT协议介绍

    1 MQTT协议简介 MQTT Message Queuing Telemetry Transport 消息队列遥测传输 是一个轻量的发布 订阅模式消息传输协议 是专门针对低带宽和不稳定网络环境的物联网应用设计的 特点 1 开放消息协议 易
  • Spring Data HelloWorld(三)

    在 Spring Data 环境搭建 二 的基础之上 我们改动 定义个一个接口 继承Repository类 咱们先实现一个根据名字查询 package org springdata repository import org springd
  • Python开发篇——添加mysqlclient

    最近使用mysql8 0 于是我就尝试用Django的框架 但是执行poetry add mysqlclient却出现了错误 python3 7 dison dison X450LD workstation project script s
  • Kuberneters企业级容器云平台落地实践之二

    九 日志中心 1 filebeat安装 Filebeat 是一个用于转发和集中日志数据的轻量级传送器 作为代理安装在您的服务器上 Filebeat 监控您指定的日志文件或位置 收集日志事件 并将它们转发到Elasticsearch或 Log
  • Linux下装载Qt

    Linux下装载Qt 官网文件下载Qt 本官网地址 http download qt io archive qt 5 9 5 9 6 https www qt io offline installers 将文件放置Linux目录下 将随意一
  • 6.SpringBoot Web开发-webjars&静态资源映射规则(欢迎页和角标favicon.ico替换)

    文章总结 作为一个后端开发 在Springboot中怎样引入需要的js依赖以及常用的静态资源映射呢 SpringBoot已经给做好了自动化配置 使用时只需要按照默认的配置去放相应的文件 就可以快速上手 1 创建SpringBoot web项