> 文档中心 > Spring Boot 静态资源访问

Spring Boot 静态资源访问


静态资源访问

Spring Boot 静态资源访问
最近在做SpringBoot项目的时候遇到了“白页”问题,通过查资料和问老师对SpringBoot访问静态资源做了如下总结。

Spring Boot 访问静态资源

在 SpringBoot 项目中没有我们之前常规 web 开发的WebContent(WebApp),它只有 src 目录。在 src/main/resources 下面有两个文件夹,static 和 templates。SpringBoot 默认在 static 目录中存放静态页面,而 templates 中放动态页面。

1 static 目录

  Spring Boot 通过 classpath/static 目录访问静态资源。注意存放静态资源的目录名称必须是 static。
  • 将静态资源放在此目录下,通过浏览器直接可以访问
    在这里插入图片描述
    在这里插入图片描述
  • 也可以通过Controller访问
    在这里插入图片描述

2 templates 目录

  在 Spring Boot 中一般使用 jsp 作为视图层技术,而是默认使用 Thymeleaf 来做动态页面。Templates 目录这是存放 Thymeleaf 的页面。  如果要想在Templates目录下面访问到html页面,可以用下面这段代码

在这里插入图片描述
Spring Boot 静态资源访问

3 静态资源存放其他位置

3.1 Spring Boot 访问静态资源的位置(优先级按以下顺序)
classpath默认就是resources,所以classpath:/static/ 就是resources/static/

classpath:/META‐INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/

3.2 自定义静态资源位置
我们可以直接通过application.properties的配置文件进行配置,如:
Spring Boot 静态资源访问
在这里插入图片描述
配置之后将html页面放到haha文件夹下后也能通过localhost:8888/index.html进行访问。( 注意:这个地方要加上.html )
Spring Boot 静态资源访问