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,如图