Spring Boot 系列(四)靜態資源處理

在web開發中,靜態資源的訪問是必不可少的,如:圖片、js、css 等資源的訪問。

spring Boot 對靜態資源訪問提供了很好的支持,基本使用默認配置就能知足開發需求。

1、默認靜態資源映射

Spring Boot 對靜態資源映射提供了默認配置css

Spring Boot 默認將 /** 全部訪問映射到如下目錄:

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

如:在resources目錄下新建 public、resources、static 三個目錄,並分別放入 a.jpg b.jpg c.jpg 圖片

目錄

瀏覽器分別訪問:

http://localhost:8080/a.jpg
http://localhost:8080/b.jpg
http://localhost:8080/c.jpg

均能正常訪問相應的圖片資源。那麼說明,Spring Boot 默認會挨個從 public resources static 裏面找是否存在相應的資源,若是有則直接返回。

2、自定義靜態資源映射

在實際開發中,可能須要自定義靜態資源訪問路徑,那麼能夠繼承WebMvcConfigurerAdapter來實現。web

第一種方式:靜態資源配置類

package com.sam.demo.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 配置靜態資源映射
 * @author sam
 * @since 2017/7/16
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //將全部/static/** 訪問都映射到classpath:/static/ 目錄下
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

重啓項目,訪問:http://localhost:8080/static/c.jpg 能正常訪問static目錄下的c.jpg圖片資源。

第二種方式:在application.properties配置

在application.properties中添加配置:

spring.mvc.static-path-pattern=/static/**

重啓項目,訪問:http://localhost:8080/static/c.jpg 一樣能正常訪問static目錄下的c.jpg圖片資源。

注意:經過spring.mvc.static-path-pattern這種方式配置,會使Spring Boot的默認配置失效,也就是說,/public /resources 等默認配置不能使用。

配置中配置了靜態模式爲/static/,就只能經過/static/來訪問。

版權聲明:本文爲博主原創文章,轉載請註明出處。spring

相關文章
相關標籤/搜索