Springboot的web开发中static和templates的区别

1.新建一个SpringBoot Maven项目

1.1 依赖设置(选中web和Thymeleaf)

这里写图片描述
这里写图片描述

1.2 resource结构如下

这里写图片描述

2. static目录

2.1 在static下新建hello1.html

运行程序,浏览器输入http://localhost:8080/hello1.html
这里写图片描述

so,可以在根目录下访问hello1.html,static目录类似于传统Java web中的webroot或webcontent

2.2 也可以通过接口跳转

2.2.1 添加接口

    @RequestMapping("hello1")
    public String hello1() {

        return "hello1.html";
    }
  • 1
  • 2
  • 3
  • 4
  • 5

2.2.2 注释掉thymeleaf依赖

    <dependencies>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-thymeleaf</artifactId>-->
        <!--</dependency>-->
  • 1
  • 2
  • 3
  • 4
  • 5

2.2.3 浏览器输入http://localhost:8080/hello1

这里写图片描述

3. template目录

3.1 在template下新建hello2.html

运行程序,浏览器输入http://localhost:8080/hello2.html
这里写图片描述

templates下的动态页面不能直接访问

3.2 通过接口访问

3.2.1 添加接口

注意接口中return的页面不包含.html后缀

    @RequestMapping("hello2")
    public String hello2() {

        return "hello2";
    }
  • 1
  • 2
  • 3
  • 4
  • 5

3.2.2 浏览器输入http://localhost:8080/hello2

这里写图片描述

4.总结

静态页面的return默认是跳转到/static/目录下,当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/下,注意看两者return代码也有区别,动态没有html后缀。

原文链接:https://blog.csdn.net/weixin_37891479/article/details/82117175

原文地址:https://www.cnblogs.com/uzxin/p/13625811.html