Thymeleaf无法显示模板视图,加载页面显示404状态问题的解决方法

本篇文章主要讲解:Thymeleaf无法显示模板视图,加载页面显示404状态问题的解决方法
日期:2024年2月23日
作者:任聪聪

现象说明:

1.只返回输出模板的名称,如图:

在这里插入图片描述

2.显示报错信息:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Feb 23 23:00:32 CST 2024
There was an unexpected error (type=Not Found, status=404).

问题原因:

1.依赖没有安装正确
2.没有正确填写Thymeleaf的模板文件内容。
3.没有正确填写Controller的生命和配置。
4.缺少核心配置文件参数。
5.路径不对。

解决方法:

排查步骤一、自审相关安装情况

1.依赖信息是否是如下配置:

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

注意:位置是在<dependencies>....</dependencies>之间

2.检查是否配置,application.properties文件:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html

3.检查templates文件路径是否在,\src\main\resources\templates下:

在这里插入图片描述

4.检查模板文件是否存在th头,如果没有则也会报错:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>距离成功又近了一步~</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }
        h1 {
            color: #007bff;
        }
        p {
            font-size: 18px;
            color: #6c757d;
        }
    </style>
</head>
<body>
<h1>欢迎使用Thymeleaf模板</h1>
<p th:text="${message?:'is null'}">默认文本信息演示~~</p>
</body>
</html>

5.检查controller的注解是否是RustController:

说明:如果是controller那么建议改为RustController。

排查步骤二、检查Controller

说明:如果你的controller没有进行ModelAndView的声明那么也会不显示界面,正确的配置如下:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


public class HomeController {
    ("/")
    public ModelAndView index(ModelAndView model){
        model.addObject("message", "Hello, Thymeleaf!");
        model.setViewName("index");
        return model;
    }
}

引入Thymeleaf成功后效果:

在这里插入图片描述
end:大功告成~

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

任聪聪

创作不易,你的打赏是我的动力!

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

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

打赏作者

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

抵扣说明:

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

余额充值