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


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

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

一、默認靜態資源映射

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

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 里面找是否存在相應的資源,如果有則直接返回。

二、自定義靜態資源映射

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

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

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/來訪問。

版權聲明:本文為博主原創文章,轉載請注明出處。


免責聲明!

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



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