【问题标题】:Unable to load html pages through controller responces in spring boot无法在spring boot中通过控制器响应加载html页面
【发布时间】:2021-02-17 00:59:45
【问题描述】:

我是 Spring boot 的新手,我了解到我可以在 Thymeleaf 依赖项的帮助下通过 Controller 类加载 HTML 页面。它最初确实有效,但现在不是。这是我的控制器类

package com.example.demo2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller2 {
    @GetMapping("/test2")
    public String sdf() {
        return "index";
    }
}

这是我的 pom.xml

4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.5.发布 com.example 演示2 0.0.1-快照 演示2 Spring Boot 演示项目

<properties>
    <java.version>11</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

这是我的项目结构

【问题讨论】:

  • 你能把index.html文件移到templates文件夹下吗
  • @IsaToltar 是的,这行得通!你能解释一下为什么吗?
  • 静态文件夹用于存放您的 css、图像和 js 文件,您需要将视图文件放入模板文件夹中

标签: spring-boot maven thymeleaf


【解决方案1】:

@RestController 注释确实为 REST API 设置了不同的默认值(如内容类型等)。尝试对类使用@Controller,对方法使用@RequestMapping

【讨论】:

  • 运气不好!它引发异常:org.thymeleaf.exceptions.TemplateInputException 错误解析模板 [index],模板可能不存在或可能无法被任何已配置的模板解析器访问
  • 啊,我明白了:请将模板从 /static 移动到 /templates - static 文件夹仅用于不需要渲染的图像和 css 文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 2015-08-07
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多