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

本文详细介绍了SpringBoot中Thymeleaf模板引擎的集成方法,以及如何区分静态和动态页面的加载路径。通过对比不同场景下的页面返回方式,阐述了静态与动态页面在SpringBoot项目中的处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 原文地址:开发者导航 · 你想要的,我全都有!

众所周知,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

 原文地址:开发者导航 · 你想要的,我全都有!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开发者导航

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值