1.SpringBoot2.x目录文件结构
SpringBoot目录文件结构和官方推荐的目录规范:
src/main/java:存放代码
src/main/resources
static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
templates:存放静态页面jsp,html,tpl
config:存放配置文件,application.properties
resources:
2、引入依赖 Thymeleaf
org.springframework.boot
spring-boot-starter-thymeleaf
注意:如果不引人这个依赖包,html文件应该放在默认加载文件夹里面,
比如resources、static、public这个几个文件夹,才可以访问
3、同个文件的加载顺序,静态资源文件
Spring Boot 默认会挨个从 META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回。
Why? 这是因为源码中就是这么定义的,参考 https://blog.csdn.net/qq_34797335/article/details/80194137
4、默认配置
1)官网地址:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content
2)spring.resources.static-locations= classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
2.资源文件加载目录顺序测试
2.1 默认资源目录访问测试
在src/main/resources目录下创建resources、public目录,分别创建test.js文件,打印所属目录
启动项目访问http://localhost:8080/test.js 进行测试:
第一次访问:获取到的是src/main/resources/resources目录下的js文件,
将上面resources/test.js 这个文件改名,第二次访问:获取到的是src/main/resources/static目录下的js文件,
将上面static/test.js 这个文件改名,第三次访问:获取到的是src/main/resources/pbulic目录下的js文件
这说明了同名的资源文件,Spring Boot 加载的默认查找顺序是 resources > static > public
2.2 访问自定义资源目录下的文件
在前述步骤,将public目录的test.js改名,在src/main/resources/目录下新建自定义的templates目录,新建test.js, js内容为console.log(“file in templates”);
重新访问:http://localhost:8080/test.js,结果如下,发现无法找到文件
这是因为访问resources 、static 、public 目录之外的资源,需要手动去配置资源加载路径,在默认的配置文件 application.properties中添加如下配置,加上classpath:/templates/:
spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/,classpath:/templates/
然后再去访问:
Tips:发现一个小技巧,输入配置项值时,停顿一些,会有一个提示,点击三个点,出现Quick Definition,然后在弹出框的界面上,会显示出这个配置项所在的类名,点进去可以查看反编译出来的源码:
或者直接鼠标右键,goto Declartion or usages,就可以打开所在的类ResourceProperties(这是一个配置类)
可以看到它里面定义了默认的资源加载路径:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
2.3 访问css/图片
访问css文件: 在src/main/resources/目录下的resources 和static目录下的文件,访问时,不需要再带上resources static,默认从这两个目录下查找
测试:
访问静态图片:在static目录下创建一个images目录(名字任意),访问该目录下的图片:http://localhost:8080/images/1.png
2.4 访问html页面
如果直接访问http://localhost:8080/index.html ,则会报404的错误,这时在pom中 添加模板引擎thymeleaf依赖,刷新maven(或者直接引入spring-boot-starter-web的依赖,spring-boot-starter-web也自动依赖了spring-boot-starter-thymeleaf)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
访问结果如下,也就是说,依赖了模板引擎,springboot会自动把idnex这个逻辑视图名映射到src/main/resources目录下的index.html中去