Spring Boot訪問靜態資源css/js,你真的懂了嗎
我們用 Spring Boot 搭建 Web 應用時(如搭建一個博客),經常需要在 Html 中訪問一些靜態資源,比如:
css 樣式; js 腳本; favicon.ico 圖標等;而在 Spring Boot 中如果沒有做任何配置,是無法直接訪問靜態資源的,通常會報 404 錯誤:
Spring Boot 訪問靜態資源,默認有兩個默認目錄:
classpath/static 目錄:src/mian/resource ServletContext 根目錄下: src/main/webapp啥是 classpath呢 ?
這里簡要的介紹下,classpath 即 WEB-INF 下面的 classes 目錄 ,在 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:/static/,classpath:/public/
圖示修改:我將默認路徑改成了 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 訪問靜態資源,可以通過以下兩種方案來解決以上問題:
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.WebMvcConfigurerAdapter;/** * @author www.exception.site 異常教程 * @date 2019/2/5 * @time 14:37 * @discription **/@Configurationpublic 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內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
