zoukankan      html  css  js  c++  java
  • 05、SpringBoot的Web开发(静态资源处理)

    使用SpringBoot开发步骤

    1、创建SpringBoot应用,选中我们需要的模块

    2、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

    3、自己编写业务代码

    比如SpringBoot到底帮我们配置了什么?我们能不能修改?我们能修改哪些配置?我们能不能扩展?

    • 向容器中自动配置组件 :XXXAutoconfiguration
    • 自动配置类,封装配置文件的内容:XXXProperties

    静态资源处理

    静态资源映射规则

    在以前的开发中,我们要引入前端资源,比如css,js等文件,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面的。但是我们现在的pom文件,打包方式是为jar的方式,那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的。

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

    我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;

    有一个方法:addResourceHandlers 添加资源处理。

    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();
            //webjars配置
            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));
            }
        }
    }
    
    • 所有的 /webjars/** 请求, 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;
    • webjars:以jar包的方式引入静态资源。

    webjars

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

    使用SpringBoot需要使用Webjars,我们可以去官网了解。官网:http://www.webjars.org/。

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

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

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

    我们在浏览器中输入localhost:8080/webjars/jquery/3.3.1/jquery.js即可访问到资源。

    自己的静态资源映射规则

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

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

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

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

    所以得出结论,以下四个目录存放的静态资源可以被我们识别:classpath:类路径即为resources路径下

    # 优先级从高到低
    "classpath:/META-INF/resources/"
    "classpath:/resources/"
    "classpath:/static/"
    "classpath:/public/"
    "/":当前项目根路径
    

    比如访问"classpath:/static/"下即resources/static/js/jquery.js。我们只需在浏览器中输入localhost:8080/js/jquery.js即可。

    自定义静态资源路径

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

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

    一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了。

    首页

    在webMvcAutoConfiguration类中我们可以找到欢迎页配置的代码。

    @Bean
    public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
       ......
    }
    private Optional<Resource> getWelcomePage() {
      ......
    }
    private Resource getIndexHtml(String location) {
        return this.resourceLoader.getResource(location + "index.html");
    }
    

    我们根据上面代码找到WelcomePageHandlerMapping

    WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
        if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage.get());//获得欢迎页
            this.setRootViewName("forward:index.html");
        } else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
            logger.info("Adding welcome page template: index");
            this.setRootViewName("index");
        }
    }
    

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

    访问localhost:8080/时,默认就会找/**下所有的index页面,所有我们只需要在能被/**映射的路径下放置index.html页面即可。

    网站图标

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

    Spring Boot 2.2.0 以前的版本设置浏览器图标

    1、关闭SpringBoot默认图标

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

    2、自己放一个图标在静态资源目录下

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

    自 SpringBoot 2.2.0+ 版本之后,原本自定义浏览器图标的方式已经无法使用,设置和原来html设置图标的方式一样。
    在首页 index.html 中设置。

    <link rel="icon" type="image/x-icon" href="favicon.ico"><!--路径根据自己的改-->
    
    coydone的博客
  • 相关阅读:
    jQuery中的一些操作
    laravel使用消息队列
    Laravel的开发环境Homestead的搭建与配置
    python爬虫学习
    配置文件
    sql根据时间差查询数据
    Oracle根据连接字符串获取库下的表列表、获取表结构
    Sql根据连接字符串获取库下的表列表、获取表结构
    判断网络连接
    线程锁,解决多线程并发问题
  • 原文地址:https://www.cnblogs.com/coydone/p/13821183.html
Copyright © 2011-2022 走看看