Spring boot 中无法显示 index.html 页面

Ime*_*sam 2 java thymeleaf spring-boot

我试图创建一个简单的弹簧启动应用程序

我创建了 spring boot 应用程序类、配置类、控制器类和 index.html。

我添加了 Thymeleaf 依赖项并将 html 页面放在资源文件夹下 (\src\main\resources\templates\index.html)

但是当我运行应用程序时它会出错

org.thymeleaf.exceptions.TemplateInputException:
Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers
Run Code Online (Sandbox Code Playgroud)

请给我一个解决方案。

@SpringBootApplication
@ComponentScan(basePackages = {"com.mail"})
public class SpringBootWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器类

@RestController
public class IndexController {

    @RequestMapping(value="/", method = RequestMethod.GET)
    String index(){
        System.out.println("..............hit");
        return "index";
    }
Run Code Online (Sandbox Code Playgroud)

Thymeleaf 的 Web 配置

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter{
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
Run Code Online (Sandbox Code Playgroud)

index.html 页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <title>Spring Framework</title>
</head>
<body>
    <h1> Hello Spring Boot </h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试执行以下操作:

  1. 用@Controller 替换@RestController;
  2. 我认为你不需要 WebConfiguration;控制器返回“index”,意思是“渲染 index.html 模板”。Thymeleaf 将在资源/模板文件夹中找到模板。