前言
spring boot放置静态资源的位置有五个位置,默认在main\wabapp中,在开发阶段修改静态资源信息不需要重启服务,如果时放置在resources下,修改html内容等需要重启服务才能生效,是业务会将资源打包到服务中。
默认位置
在 Spring Boot 中,默认情况下,一共有5个位置可以放静态资源,五个路径分别是如下5个:
1.classpath:/META-INF/resources/
2.classpath:/resources/
3.classpath:/static/
4.classpath:/public/
5./
前四个目录好理解,分别对应了resources目录下不同的目录,第5个 “/” 是啥意思呢?我们知道,在 Spring Boot 项目中,默认是没有 webapp 这个目录的,当然我们也可以自己添加(例如在需要使用JSP的时候),这里第5个 “/” 其实就是表示 webapp 目录中的静态资源也不被拦截。如果同一个文件分别出现在五个目录下,那么优先级也是按照上面列出的顺序。
不过,虽然有5个存储目录,除了第5个用的比较少之外,其他四个,系统默认创建了 classpath:/static/ , 正常情况下,我们只需要将我们的静态资源放到这个目录下即可,也不需要额外去创建其他静态资源目录。
webapp配置
目录结构
访问资源时默认只能服务webapp中的文件,如果需要访问WIN-INF下的second.html文件则需要加路径,如访问index.html可访问http://localhost:5137/index.html,或http://localhost:5137,访问second.html则需要访问http://localhost:5137/WIN-INF/second.html
配置
如果不想在请求的时候添加路径和文件类型,则可以配置通用接口
application.yml中的配置
spring:
mvc:
view:
prefix: /WIN-INF/
controller中的代码
@Controller
public class StaticHtml {
// 用于转发html
@GetMapping("{param}")
public String getHtml(@PathVariable(name = "param") String param){
return param+".html";
}
// 用于index的转发,http://localhost:5137可直接访问index.html
@GetMapping("{param}.html")
public String getHtml1(@PathVariable(name = "param") String param){
return param+".html";
}
@GetMapping("jsfile/{param}.js")
public String getJs(@PathVariable(name = "param") String param){
return "jsfile/"+param+".js";
}
}
访问second.html则需要访问http://localhost:5137/second,访问testJs.js则可以使用http://localhost:5137/jsfile/testJs.js,js和css类似,最好带格式
resources配置
目录结构
配置
application.yml配置
spring:
resources:
static-locations: classpath:/
mvc:
static-path-pattern: /**
默认访问路径为resources中其它同webapp中的配置