Spring Boot訪問靜態資源css/js,你真的懂了嗎
一、前言
我們用 Spring Boot 搭建 Web 應用時(如搭建一個部落格),經常需要在 Html 中訪問一些靜態資源,比如:
而在 Spring Boot 中如果沒有做任何配置,是無法直接訪問靜態資源的,通常會報 404 錯誤:
二、Spring Boot 訪問靜態資源的預設目錄
Spring Boot 訪問靜態資源,預設有兩個預設目錄:
classpath/static
目錄:src/mian/resource
ServletContext
根目錄下:src/main/webapp
啥是 classpath
呢 ?
這裡簡要的介紹下,classpath
即 WEB-INF 下面的 class程式設計客棧es 目錄 ,在 Spring Boot 專案中就是src/main/resource
目錄。
2.1 classpath 目錄下-訪問預設資料夾名為 static
專案目錄截圖:
訪問截圖:
這裡有人就想說,我可不可以修改一下訪問路徑呢,答案是肯定的,肯定可以。
在 properties
檔案裡面設定 spring.resources.static-locations
就ok了。
spring.resources.static-locations
的預設值是:classpath:/META-INF/resources/,classpath:/resources/,classpath
圖示修改:我將預設路徑改成了 src/main/resource/static/images/
,在裡面我寫了一個 index.html 裡面寫的 html img
訪問的時候就找的是我設定的路徑了。
2.2 ServletContext 根目錄下( src/main/webapp ) - webapp 就是預設訪問資料夾
這個可能很多人就不陌生了,一般來說 src/main/java
裡面放Java程式碼,resource
裡面放配置檔案,xml, webapp裡面放頁面,js之類的。
ServletContent 根目錄就是 src/main/webapp
一般建立的maven專案裡面都沒有 webapp 資料夾,在這裡我們自己在 src/main
目錄下建立一個 webapp
專案目錄,以及訪問截圖:
三、Spring Boot 訪問靜態資源解決方案
上面知識點主要做些科普,至於如何在 Spring Boot 訪問靜態資源,可以通過以下兩種方案來解決以上問題:
3.1 第一種方案(推薦)
修改 application.yml
,新增以下配置:
# 放開 Spring Boot 專案中 /static 目錄下靜態資源的攔截 spring: mvc: static-path-pattern: /static/**
application.properties
檔案新增如下:
spring.mvc.static-path-pattern=/static/**
3.2 第二種方案
新增一個 WebMvcConfig.java
配置類,告訴 springboot 靜態資源的載入路徑:
package com.exception.qms.config; import org.springframework.context.annotation.Configuration程式設計客棧; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerA程式設計客棧dapter; /** * @author www.exception.site 異常教程 *www.cppcns.com @date 2019/2/5 * @time 14:37 * @discription **/ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } }
二選一,新增完成後,我們就可以在 Spring Boot 中正常訪問靜態資源辣~
到此這篇關於Spring Boot訪問靜態資源css/js你真的懂了嗎的文章就介紹到這了,更多相關Spring Boot靜態資源css/js內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!