Spring 未提供 html 文件

Spring not serving html file

所以我正在尝试按照本指南了解如何使用 Spring 提供 html 文件: http://spring.io/guides/gs/serving-web-content/

我有完全相同的文件夹结构和完全相同的文件,但是当我 运行 spring 启动服务器时,我的 localhost:8080/greeting 将只显示字符串 greetingGreetingController 返回,仅此而已,如果我查看页面源代码,其中没有 html。

我找不到关于此的任何相关答案,因为所有类似的答案仍然使用 .xml 文件驱动 Spring,您在 .xml 文件中声明视图。但是本指南明确表示不需要使用 .xml 。它应该像那样工作。

映射:

@RestController
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required = false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

使用@Controller 抛出错误:

2015-02-25 14:50:14.830 ERROR 2378 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [greeting]: would dispatch back to the current handler URL [/greeting] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause

javax.servlet.ServletException: Circular view path [greeting]: would dispatch back to the current handler URL [/greeting] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

编辑:

解决方法: a) 使用 @Controller 而不是 @RestController b) 在 IntelliJ 中启动应用程序时,确保在执行 Main class.

之前创建一个 Gradle 任务 运行

您正在使用 @RestControllerdocumentation)而不是 @Controller

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

@ResponseBody 只是 return 给调用者,无论方法 returns,字符串 greeting 在你的情况下。

至于你得到的Circular view path exception,它可能与ViewResolvers有关。来自 spring 引导文档

There are many implementations of ViewResolver to choose from, and Spring on its own is not opinionated about which ones you should use. Spring Boot, on the other hand, installs one or two for you depending on what it finds on the classpath and in the application context

因此,依赖项中可能缺少某些内容。您是否配置了 spring-boot-starter-thymeleaf 依赖项?

您是否在 pom.xml 中添加了以下依赖项?

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