zoukankan      html  css  js  c++  java
  • SpringBoot WEB开发静态文件处理和主页

    SpringBoot WEB开发静态文件处理和主页

    静态文件处理

    SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;

    我们可以去看看 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();
        // webjars 配置
        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/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;

    第一种静态资源映射规则 webjars ?

    Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。

    使用SpringBoot需要使用Webjars,我们可以去搜索一下:

    网站:https://www.webjars.org

    要使用jQuery,我们只要要引入jQuery对应版本的pom依赖即可!

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

    导入完毕,查看webjars目录结构,并访问Jquery.js文件!

    第二种静态资源映射规则(常用)

    那我们项目中要是使用自己的静态资源该怎么导入呢?我们看下一行代码;

    我们去找staticPathPattern发现第二种映射规则 :/** , 访问当前的项目任意资源,它会去找 resourceProperties 这个类,我们可以点进去看一下分析:

    // 进入方法
    public String[] getStaticLocations() {
        return this.staticLocations;
    }
    // 找到对应的值
    private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
    // 找到路径
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
        "classpath:/META-INF/resources/",
      "classpath:/resources/", 
        "classpath:/static/", 
        "classpath:/public/" 
    };
    

    ResourceProperties 可以设置和我们静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。

    所以得出结论,以下四个目录存放的静态资源可以被我们识别:

    加载顺序优先级: 1 > 2 > 3 > 4, 即1优先级最高

    1. "classpath:/META-INF/resources/"
    2. "classpath:/resources/"
    3. "classpath:/static/"
    4. "classpath:/public/"
    

    我们可以在resources根目录下新建对应的文件夹,都可以存放我们的静态文件;

    比如我们访问 http://localhost:8080/1.js , 他就会去这些文件夹中寻找对应的静态资源文件;

    我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;

    spring.resources.static-locations=classpath:/coding/,classpath:/aaabbb/
    

    首页处理

    我们继续向下看源码!可以看到一个欢迎页的映射,就是我们的首页!

    @Bean
    public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
                                                               FormattingConversionService mvcConversionService,
                                                               ResourceUrlProvider mvcResourceUrlProvider) {
        WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
            new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // getWelcomePage 获得欢迎页
            this.mvcProperties.getStaticPathPattern());
        welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
        return welcomePageHandlerMapping;
    }
    

    点进去继续看

    private Optional<Resource> getWelcomePage() {
        String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
        // ::是java8 中新引入的运算符
        // Class::function的时候function是属于Class的,应该是静态方法。
        // this::function的funtion是属于这个对象的。
        // 简而言之,就是一种语法糖而已,是一种简写
        return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
    }
    // 欢迎页就是一个location下的的 index.html 而已
    private Resource getIndexHtml(String location) {
        return this.resourceLoader.getResource(location + "index.html");
    }
    

    欢迎页,静态资源文件夹下的所有 index.html 页面;被 /** 映射。

    比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html

    新建一个 index.html ,在我们上面的3个目录中任意一个;然后访问测试 http://localhost:8080/ 看结果!

    关于网站图标说明

    与其他静态资源一样,Spring Boot在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。

    1、关闭SpringBoot默认图标

    #关闭默认图标spring.mvc.favicon.enabled=false
    

    2、自己放一个图标在静态资源目录下,例如放在 public 目录下, 文件名favicon.ico

    3、清除浏览器缓存!刷新网页,发现图标已经变成自己的了!

  • 相关阅读:
    SQL注入攻击
    新手指引,php什么是常量、变量、数组、类和对象及方法?
    JQuery坑,说说哪些大家都踩过的坑
    利用Jsonp实现跨域请求,spring MVC+JQuery
    【实用】需要收藏备用的JQuery代码片段
    【动画】JQuery实现冒泡排序算法动画演示
    【基础】26个命令玩转linux,菜鸟及面试必备
    【收藏】8段JQuery处理表单的代码片段,很实用
    【实用】Html5实现文件异步上传
    【基础】新手任务,五分钟全面掌握JQuery选择器
  • 原文地址:https://www.cnblogs.com/zpKang/p/13254602.html
Copyright © 2011-2022 走看看