springboot的請求路徑通常會通過Controller處理,可是靜態資源文件在請求以後是直接返回的。這涉及到倆個配置項。html
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
上面倆個是他們的默認配置,若是項目中沒有任何配置,項目會以這種配置執行。
spring.mvc.static-path-pattern指的是請求路徑。
spring.resources.static-locations指的是,靜態資源目錄,目錄按配置順序由先到後,優先級由高到低。
舉例說明:
若是配置爲
spring.mvc.static-path-pattern:/static/**,
spring.resources.static-locations:classpath:/static/,classpath:/public/
即http://localhost:8088/static/index.html的請求會是一個靜態請求;而http://localhost:8088/index.html的請求不是一個靜態請求。
那麼http://localhost:8088/static/index.html這個請求,就會在如今static目錄下,尋找index.html文件(注意:尋找的是index.html文件,而不是static/index.html),若是找到了響應請求,若是找不到,再在public文件夾下尋找。在須要注意的是,在
另外:spring是先處理Controller請求的,當項目中有處理static/index.html路徑的方法時,如圖:
請求是不會去尋找靜態資源的。web
這種配置方式是在application.properties文件中配置的,除此以後還能夠在項目中配置。
項目中配置方式:
package com.tsinkai.ettp.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); } }
這兩種方式的配置是同事存在的,並不衝突。spring
另外寫在html中的靜態路徑須要注意的問題:springboot
正確寫法:<script src="/static/layui/layui.js">mvc
錯誤寫法:<script src="static/layui/layui.js">app
static前的/,必定要寫好,不然會在請求js時出現404.ide
緣由:ui
正確請求的路徑:http://localhost:8088/static/layui/layui.jsspa
錯誤請求的路徑:http://localhost:8088/thymeleaf/static/layui/layui.jscode
即,若是不寫/,那麼最終的請求會加上處理該請求的Controller類的RequestMapping,如圖