Spring Boot 靜態資源文件配置 A卷

Spring Boot 靜態資源文件配置

說在前面的話:

  • 創建SpringBoot應用,選中我們需要的模塊
  • SpringBoot已經默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來
  • 自己編寫業務代碼
由於 Spring Boot 採用了”約定優於配置”這種規範,所以在使用靜態資源的時候也很簡單。

SpringBoot本質上是爲微服務而生的,以JAR的形式啓動運行,但是有時候靜態資源的訪問是必不可少的,比如:image、js、css 等資源的訪問

1.webjars配置靜態路徑

簡單瞭解即可,感覺實用性不大,

public class WebMvcAutoConfiguration {
         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(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }
}

代碼分析: 所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源;webjars:以jar包的方式引入靜態資源; webjars提供的依賴官網

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

啓動服務,測試訪問靜態地址http://127.0.0.1:8001/hp/webjars/jquery/1.12.4/jquery.js

2.默認靜態資源路徑

@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;

    public ResourceProperties() {
        this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
        this.addMappings = true;
        this.chain = new ResourceProperties.Chain();
        this.cache = new ResourceProperties.Cache();
    }

    public String[] getStaticLocations() {
        return this.staticLocations;
    }
}

摘抄了部分源碼,算是爲了增加篇幅,從上述代碼中我們可以看到,提供了幾種默認的配置方式

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
備註說明: "/"=>當前項目的根路徑

我們在src/main/resources目錄下新建 public、resources、static 、META-INF等目錄目錄,並分別放入 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 五張圖片。

注意:需要排除webjars的形式,將pom.xml中的代碼去掉,在進行測試結果結果如下

3.新增靜態資源路徑

我們在spring.resources.static-locations後面追加一個配置classpath:/os/

# 靜態文件請求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默認的靜態尋址資源目錄 多個使用逗號分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/os/

4.自定義靜態資源映射

在實際開發中,我們可能需要自定義靜態資源訪問以及上傳路徑,特別是文件上傳,不可能上傳的運行的JAR服務中,那麼可以通過繼承WebMvcConfigurerAdapter來實現自定義路徑映射。

application.properties 文件配置:

# 圖片音頻上傳路徑配置(win系統自行變更本地路徑)
web.upload.path=D:/upload/attr/

Demo05BootApplication.java 啓動配置:

package com.hanpang;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class Demo05BootApplication implements WebMvcConfigurer {
    private final static Logger LOGGER = LoggerFactory.getLogger(Demo05BootApplication.class);

    @Value("${web.upload.path}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**").addResourceLocations(
                "file:" + uploadPath);
        LOGGER.info("自定義靜態資源目錄、此處功能用於文件映射");
    }

    public static void main(String[] args) {
        
        SpringApplication.run(Demo05BootApplication.class, args);
    }

}

5.設置歡迎界面

依然從源碼出手來解決這個問題

public class WebMvcAutoConfiguration {
            private Optional<Resource> getWelcomePage() {
            String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

        private Resource getIndexHtml(String location) {
            return this.resourceLoader.getResource(location + "index.html");
        }
}

5.1 直接設置靜態默認頁面

歡迎頁; 靜態資源文件夾下的所有index.html頁面,被"/**"映射;

5.2 增加控制器的方式

  • 新增模版引擎的支持

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  • 配置核心文件application.properties

    server.port=8001
    server.servlet.context-path=/hp
    spring.mvc.view.prefix=classpath:/templates/

    沒有去設置後綴名

  • 設置增加路由

    @Controller
    public class IndexController {
        @GetMapping({"/","/index"})
        public String index(){
            return "default";
        }
    }
  • 訪問http://127.0.0.1:8001/hp/

5.3 設置默認的View跳轉頁面

  • 新增模版引擎的支持

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  • 配置核心文件application.properties

    server.port=8001
    server.servlet.context-path=/hp
    spring.mvc.view.prefix=classpath:/templates/

    沒有去設置後綴名

  • 啓動文件的修改如下

    @SpringBootApplication
    public class Demo05BootApplication implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("default");
            registry.addViewController("/index1").setViewName("default");
            registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        }
    
        public static void main(String[] args) {
    
            SpringApplication.run(Demo05BootApplication.class, args);
        }
    
    }

6. Favicon設置

 @Configuration
        @ConditionalOnProperty(
            value = {"spring.mvc.favicon.enabled"},
            matchIfMissing = true
        )
        public static class FaviconConfiguration implements ResourceLoaderAware {
            private final ResourceProperties resourceProperties;
            private ResourceLoader resourceLoader;

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

            public void setResourceLoader(ResourceLoader resourceLoader) {
                this.resourceLoader = resourceLoader;
            }

            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(-2147483647);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
                return mapping;
            }

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

            private List<Resource> resolveFaviconLocations() {
                String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
                List<Resource> locations = new ArrayList(staticLocations.length + 1);
                Stream var10000 = Arrays.stream(staticLocations);
                ResourceLoader var10001 = this.resourceLoader;
                var10001.getClass();
                var10000.map(var10001::getResource).forEach(locations::add);
                locations.add(new ClassPathResource("/"));
                return Collections.unmodifiableList(locations);
            }
        }

SpringBoot 默認是開啓Favicon,並且提供了一個默認的Favicon,如果想關閉Favicon,只需要在application.properties中添加

spring.mvc.favicon.enabled=false

如果想更改Favicon,只需要將自己的Favicon.ico(文件名不能改動),放置到類路徑根目錄、類路徑META_INF/resources/下、類路徑resources/下、類路徑static/下或者類路徑public/下。

5.附錄

A.WebMvcConfigurerAdapter過時

在Springboot中配置WebMvcConfigurerAdapter的時候發現這個類過時了。所以看了下源碼,發現官方在spring5棄用了WebMvcConfigurerAdapter,因爲springboot2.0使用的spring5,所以會出現過時。

WebMvcConfigurerAdapter已經過時,在新版本中被廢棄,以下是比較常用的重寫接口:

/** 解決跨域問題 **/
public void addCorsMappings(CorsRegistry registry) ;
/** 添加攔截器 **/
void addInterceptors(InterceptorRegistry registry);
/** 這裏配置視圖解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);
/** 配置內容裁決的一些選項 **/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 視圖跳轉控制器 **/
void addViewControllers(ViewControllerRegistry registry);
/** 靜態資源處理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);
/** 默認靜態資源處理器 **/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);

方案1:直接實現WebMvcConfigurer

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

方案2:直接繼承WebMvcConfigurationSupport

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

其實,源碼下WebMvcConfigurerAdapter是實現WebMvcConfigurer接口,所以直接實現WebMvcConfigurer接口也可以;WebMvcConfigurationSupport與WebMvcConfigurerAdapter、接口WebMvcConfigurer處於同一個目錄下WebMvcConfigurationSupport包含WebMvcConfigurer裏面的方法,由此看來版本中應該是推薦使用WebMvcConfigurationSupport類的,WebMvcConfigurationSupport應該是新版本中對WebMvcConfigurerAdapter的替換和擴展

B.關於加載目錄問題

// 可以直接使用addResourceLocations 指定磁盤絕對路徑,同樣可以配置多個位置,注意路徑寫法需要加上file:
registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");
// 訪問myres根目錄下的fengjing.jpg 的URL爲 http://localhost:8080/fengjing.jpg (/** 會覆蓋系統默認的配置)
registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章