3、如果你沒有特別配置靜態資源的位置,那么默認的靜態資源的位置就是resource 下面的static 文件夾,畢竟不用自己新建文件夾,那么你的頁面引入的靜態文件可以這么寫:
<script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script>
4、當然就需要在static下面創建js文件夾,將jqeruy.js放在這個js文件夾下面。
5、或者你習慣於在webapp下面寫靜態文件,那么需要注意兩個點:
1)、第一點:需要在webapp下面創建一個static文件夾(和WEB-INF同級) 然后創建js文件夾,然后把靜態文件放進去
2)、第二點:引入靜態文件的寫法:
<script type="text/javascript" src="/static/js/jquery-3.4.1.min.js"></script>
注意上面都是沒有指定靜態文件的地址的,指定靜態文件的地址的屬性是 : spring.resources.static-locations
可以在application.properties中指定靜態資源的地址,如下所示:
1 spring.resources.static-locations=classpath:*/js/,classpath:*/css/
如果不指定的,默認值有四個:Default:
classpath:/META-INF/resources/,
classpath:/resources/,
classpath:/static/,
classpath:/public/
6、使用案例,如下所示:
需要注意的是如果spring.resources.static-locations、spring.mvc.static-path-pattern配置如下的值:
1 spring.mvc.view.prefix=/WEB-INF/jsp/ 2 spring.mvc.view.suffix=.jsp 3 spring.resources.static-locations=classpath:/static/ 4 spring.mvc.static-path-pattern=/static/**
備注:
spring.mvc.static-path-pattern: spring.mvc.static-path-pattern,這個配置就是在訪問靜態資源的路徑前面追加static關鍵字。比如沒有設置這個配置項之前,訪問靜態資源http://127.0.0.1/js/jquery.bootstrap.js,加了之后就要這樣訪問了 http://127.0.0.1/static/js/jquery.bootstrap.js。
spring.resources.static-locations: classpath:/static,classpath:/templates,這個是用以指定存放靜態資源的路徑,查找靜態資源時會上面的路徑下面開始搜索,沒有找到會返回404。
或者實現了addResourceHandlers該方法里面的所示內容,那么靜態資源引用的時候,前面要加上/static/的,不然無法進行引用。
1 package com.fline.datagovern.config; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 5 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 7 8 /** 9 * 10 * @author biehl 11 * 12 */ 13 @Configuration 14 public class SpringMvcWebConfigSupport implements WebMvcConfigurer { 15 16 /** 17 * 將static下面的js,css等等文件加載出來 18 * 19 * @param registry 20 */ 21 // @Override 22 // public void addResourceHandlers(ResourceHandlerRegistry registry) { 23 // registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); 24 // } 25 26 /** 27 * 默認訪問的是登錄界面 28 * 29 * springboot 默認的靜態資源的值有四個:Default: 30 * 31 * classpath:/META-INF/resources/, 32 * 33 * classpath:/resources/, 34 * 35 * classpath:/static/,默認的靜態資源的位置就是resource下面的static文件夾 36 * 37 * classpath:/public/ 38 */ 39 @Override 40 public void addViewControllers(ViewControllerRegistry registry) { 41 // 瀏覽器發送/請求來到login.jsp頁面,不用寫controller控制層的請求方法了 42 // http://127.0.0.1:8000/xxx/ 43 registry.addViewController("/").setViewName("login"); 44 } 45 46 }
引用效果,如下所示: