SpringBoot靜態資源文件位置


SpringBoot可以JAR/WAR的形式啟動運行,有時候靜態資源的訪問是必不可少的,比如:image、js、css 等資源的訪問。

一、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提供的依賴官網

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

啟動服務,測試訪問靜態地址:

http://127.0.0.1:9091/hp/webjars/jquery/3.4.1/jquery.js(hp是應用上下文, server.servlet.context-path = /hp)

二、默認靜態資源路徑

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
            "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

    /**
     * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
     * /resources/, /static/, /public/].
     */
    private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

    /**
     * Whether to enable default resource handling.
     */
    private boolean addMappings = true;

    private final Chain chain = new Chain();

    private final Cache cache = new Cache();

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

    public void setStaticLocations(String[] staticLocations) {
        this.staticLocations = appendSlashIfNecessary(staticLocations);
    }

    private String[] appendSlashIfNecessary(String[] staticLocations) {
        String[] normalized = new String[staticLocations.length];
        for (int i = 0; i < staticLocations.length; i++) {
            String location = staticLocations[i];
            normalized[i] = location.endsWith("/") ? location : location + "/";
        }
        return normalized;
    }

    public boolean isAddMappings() {
        return this.addMappings;
    }

    public void setAddMappings(boolean addMappings) {
        this.addMappings = addMappings;
    }

    public Chain getChain() {
        return this.chain;
    }

    public Cache getCache() {
        return this.cache;
    }
        ......
        ......
}
View Code

SpringBoot提供了幾種默認的資源路徑:

classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/

備注說明: "/"=>當前項目的根路徑

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

 

訪問圖片地址:http://127.0.0.1:9091/hp/1.jpg,只有5.jpg訪問不到。

springboot訪問靜態資源,默認有兩個默認目錄:

  • 一個是 src/mian/resource目錄(上面將的就是這種情況)
  • 一個是 ServletContext 根目錄下( src/main/webapp )

一般來說 src/main/java 里面放Java代碼,resource 里面放 配置文件、xml, webapp里面放頁面、js之類的。

一般創建的maven項目里面都沒有 webapp 文件夾,在這里我們自己在 src/main 目錄下創建一個 webapp項目目錄。

三、新增靜態資源路徑

我們在 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/

四、設置歡迎界面

源碼:

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");
        }
}

1. 直接設置靜態默認頁面

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

2. 增加控制器的方式

(1) 新增模版引擎的支持

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

(2) 配置核心文件application.properties

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

沒有設置后綴名。

(3) 設置路由

@Controller
public class IndexController {
    @GetMapping({"/","/index"})
    public String index(){
        return "default";
    }
}

訪問http://127.0.0.1:9091/hp/。

3. 設置默認的View跳轉頁面

(1) 新增模版引擎的支持

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

(2) 配置核心文件application.properties

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

(3) 啟動文件的修改如下

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

}

4. 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;
    }

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

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

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

    private List<Resource> resolveFaviconLocations() {
        String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
        List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
        Arrays.stream(staticLocations).map(this.resourceLoader::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/下。

五、WebMvcConfigurer接口

1. 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的替換和擴展。
2. 關於加載目錄問題
// 可以直接使用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/");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM