springboot集成Thymeleaf时页面跳转和路径问题

众所周知,springboot简化了框架整合的相关配置。默认static中放静态页面,templates中放动态页面。

springboot集成Thymeleaf时页面跳转和路径问题

编写测试代码

新建两个页面分别放到static和templates目录下。

static/hello.html

1

2

3

4

5

6

7

8

9

10

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <h2>static...hello.html</h2>

</body>

</html>

templates/hello.html

1

2

3

4

5

6

7

8

9

10

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<h2>templates...hello.html</h2>

</body>

</html>

新建一个controller,内容如下:注意看两个方法return代码的区别,动态没有html后缀

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

package com.example.demo;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

/**

 * springboot集成Thymeleaf时页面跳转和路径问题

 * @author jiagou1216.com

 */

@Controller

public class TestController {

 

    @RequestMapping("/hello1")

    public String sayHello1() {

        return "hello";

    }

 

    @RequestMapping("/hello2")

    public String sayHello2() {

        return "hello.html";

    }

}

注意:此时我们没有在pom.xml文件中引入thymeleaf的jar包

springboot集成Thymeleaf时页面跳转和路径问题

测试一下:

http://localhost:8080/hello1,动态访问,404,找不到页面

springboot集成Thymeleaf时页面跳转和路径问题

http://localhost:8080/hello2,静态访问,访问static目录下的静态资源

springboot集成Thymeleaf时页面跳转和路径问题

http://localhost:8080/hello.html,静态访问,访问static目录下的静态资源

springboot集成Thymeleaf时页面跳转和路径问题

添加模板引擎

在pom.xml文件中引入thymeleaf的jar包后,再次测试

1

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

http://localhost:8080/hello1,动态访问,访问templates目录下的动态资源

springboot集成Thymeleaf时页面跳转和路径问题

http://localhost:8080/hello2,动态访问,访问templates目录下的动态资源

springboot集成Thymeleaf时页面跳转和路径问题

http://localhost:8080/hello.html,静态访问,访问static目录下的静态资源

springboot集成Thymeleaf时页面跳转和路径问题

 

总结:

1)直接访问http://localhost:8080/hello.html,不管有没有模板引擎都只访问static目录下的html。

2)添加模板引擎后,通过controller跳转的页面不管加不加.html后缀都只访问templates目录下的html。

原因:

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

那么问题来了,如果使用动态页面时还想跳转到/static下的静态页面该怎么办呢?

使用重定向redirect

springboot集成Thymeleaf时页面跳转和路径问题

注意观察,当浏览器中访问http://localhost:8080/hello3时,地址栏会自动变为http://localhost:8080/hello.html

springboot集成Thymeleaf时页面跳转和路径问题

原文地址:【架构师小跟班 www.jiagou1216.com】