springboot集成Thymeleaf時頁面跳轉和路徑問題

衆所周知,springboot簡化了框架整合的相關配置。默認static中放靜態頁面,templates中放動態頁面。

編寫測試代碼

新建兩個頁面分別放到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包

測試一下:

http://localhost:8080/hello1,動態訪問,404,找不到頁面

http://localhost:8080/hello2,靜態訪問,訪問static目錄下的靜態資源

http://localhost:8080/hello.html,靜態訪問,訪問static目錄下的靜態資源

添加模板引擎

在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目錄下的動態資源

http://localhost:8080/hello2,動態訪問,訪問templates目錄下的動態資源

http://localhost:8080/hello.html,靜態訪問,訪問static目錄下的靜態資源

 

總結:

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

注意觀察,當瀏覽器中訪問http://localhost:8080/hello3時,地址欄會自動變爲http://localhost:8080/hello.html

原文地址:【架構師小跟班 www.jiagou1216.com】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章