Spring Boot | Spring Boot 目录文件结构详解

一、目录结构

1.src/main/java:存放Java代码

2.src/main/resources

  • resources:(Spring Boot 默认的)存放资源文件
  • static:(Spring Boot 默认的)存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
  • public:(Spring Boot 默认的)存放公共文件
  • templates:(用户自己定义的,可以随便取名,但这里使用公认的文件名)存放静态页面,比如 jsp、html
  • config:(用户自己定义的,可以随便取名,但这里使用公认的文件名)存放配置文件,比如 application.properties
    在这里插入图片描述

二、同个文件的加载顺序,静态资源文件

Spring Boot 默认会挨个从 META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回。

比如:我们在这几个文件夹下都新建一个 js 文件,看它会去加载哪个文件?
在这里插入图片描述
地址栏输入以下地址:http://localhost:8080/test.js,这里我们没有在 resources 文件夹下建 test.js 文件,所以会去加载 static 文件夹下面的文件

三、templates文件夹

templates文件夹下的文件需要通过转发才可以访问到

因为 templates 不是 Spring Boot 默认文件夹,所以我们访问不到这个文件夹里的文件

1.要想访问,需要引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.编写一个controller

@Controller
public class jumpController {
    
    
    @RequestMapping("/index")
    public String index() {
    
    
        return "index";
    }
}

3.Thymeleaf配置文件(在application.properties进行配置)

#####Thymeleaf配置文件
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
#编码
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.check-template=true
#类型
spring.thymeleaf.servlet.content-type=text/html
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#后缀
spring.thymeleaf.suffix=.html

此时访问localhost:8080/index就可以访问到templates下的index.html

四、自己定义加载顺序或者添加自己新增的文件夹

编辑application.properties

spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 

官网说明:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

猜你喜欢

转载自blog.csdn.net/y1534414425/article/details/105992495