一、前言
我們用 Spring Boot 搭建 Web 應(yīng)用時(如搭建一個博客),經(jīng)常需要在 Html 中訪問一些靜態(tài)資源,比如:
- css 樣式;
- js 腳本;
- favicon.ico 圖標(biāo)等;
而在 Spring Boot 中如果沒有做任何配置,是無法直接訪問靜態(tài)資源的,通常會報 404 錯誤
二、Spring Boot 訪問靜態(tài)資源的默認(rèn)目錄
Spring Boot 訪問靜態(tài)資源,默認(rèn)有兩個默認(rèn)目錄:
-
classpath/static
?目錄:src/mian/resource
-
ServletContext
?根目錄下:?src/main/webapp
啥是?classpath
呢 ?
這里簡要的介紹下,classpath
?即 WEB-INF 下面的 classes 目錄 ,在 Spring Boot 項(xiàng)目中就是src/main/resource
?目錄。
2.1?classpath 目錄下-訪問默認(rèn)文件夾名為 static
項(xiàng)目目錄截圖:
這里有人就想說,我可不可以修改一下訪問路徑呢,答案是肯定的,肯定可以。
在?properties
文件里面設(shè)置?spring.resources.static-locations
?就ok了。
spring.resources.static-locations
?的默認(rèn)值是:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
圖示修改:我將默認(rèn)路徑改成了?src/main/resource/static/images/
,在里面我寫了一個 index.html 里面寫的 html img
訪問的時候就找的是我設(shè)置的路徑了。
2.2?ServletContext 根目錄下( src/main/webapp ) - webapp 就是默認(rèn)訪問文件夾
這個可能很多人就不陌生了,一般來說?src/main/java
?里面放Java代碼,resource
?里面放配置文件, xml, webapp里面放頁面,js之類的。
ServletContent 根目錄就是?src/main/webapp
一般創(chuàng)建的maven項(xiàng)目里面都沒有 webapp 文件夾,在這里我們自己在?src/main
?目錄下創(chuàng)建一個 webapp
項(xiàng)目目錄,以及訪問截圖:
三、Spring Boot 訪問靜態(tài)資源解決方案
上面知識點(diǎn)主要做些科普,至于如何在 Spring Boot 訪問靜態(tài)資源,可以通過以下兩種方案來解決以上問題:
3.1 第一種方案(推薦)
修改?application.yml
?, 添加以下配置:
# 放開 Spring Boot 項(xiàng)目中 /static 目錄下靜態(tài)資源的攔截
spring:
mvc:
static-path-pattern: /static/**
application.properties
?文件添加如下:
spring.mvc.static-path-pattern=/static/**
3.2 第二種方案
添加一個?WebMvcConfig.java
?配置類,告訴 springboot 靜態(tài)資源的加載路徑:文章來源:http://www.zghlxwxcb.cn/news/detail-711735.html
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;
/**
* @date 2020/10/7
* @time 14:37
* @discription
**/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
二選一,添加完成后,我們就可以在 Spring Boot 中正常訪問靜態(tài)資源辣~文章來源地址http://www.zghlxwxcb.cn/news/detail-711735.html
到了這里,關(guān)于Spring Boot 訪問靜態(tài)資源css/js的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!