Spring Boot v2.0没有看到模板

时间:2018-06-26 09:26:54

标签: java spring spring-boot tomcat

我尝试启动在Spring Initializr中创建的演示应用程序。 Spring Boot版本-2.0.3。

我创建了index.html并将其放入resources/templates文件夹中。当我启动spring-boot:run时,控制台状态中的消息之一:

Tomcat started on port(s): 8080 (http) with context path ''

当我打开localhost:8080时,它给了我Spring的Whitelabel错误页面

我试图在server.servlet.context-path=/文件中添加行resources/application.properties。但这无济于事。

如何为索引设置正确的路径?

UPD:似乎问题仅在于模板部分。

index.htmlresources/templates的内容:

<!DOCTYPE html>
<html lang="en">

<body>
<h1>Hello {{ name }}!!!</h1>
</body>
</html>

IndexController.java的内容:

@Controller
public class IndexController {
    @GetMapping("/")
    public ModelAndView index() {
        Map<String, String> model = new HashMap<>();
        model.put("name", "world");
        return new ModelAndView("index", model);
    }

我在pom.xml中使用胡须:

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

它给了我whitelabel错误。即使server.servlet.context-path=/中有resources/application.properties

如果我将文件放在resource/static中,然后在IndexController中将文件重命名为“ index.html”,则会显示该文件,但显然不会替换“ name”。

我该怎么办?

4 个答案:

答案 0 :(得分:2)

最后,this answer提供了帮助。似乎是胡须功能。这很奇怪,因为在SpringBoot 1.5.x中,使用空文件application.properties都可以正常工作。如果有人知道,为什么它会针对SpringBoot 2.0进行更改-在评论中分享。

答案 1 :(得分:1)

如果要提供静态内容,则需要将其放入static文件夹中的resources文件夹中。

templates在使用Thymeleaf和Spring MVC控制器等视图技术时使用。

您可以在此处找到更多信息:https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

答案 2 :(得分:1)

Spring Boot将请求定向到匹配的控制器。因此,定义一个简单的Controller类来处理请求,并将该类放置在项目的根包下方或内部的包中:

@Controller
public class MyController {

   @GetMapping(value={"/"})
   public ModelAndView getRoot()
   {
       return new ModelAndView("index");
   }
}

Controller-Annotation来自于org.springframework.stereotype包,而GetMapping-Annotation来自于org.springframework.web.bind.annotation。

也许您还需要扩展pom.xml文件。检查它是否包含依赖项spring-boot-starter-web(如果已选择“ Maven Project”)。

答案 3 :(得分:0)

您应该更改application.properties

spring.mustache.suffix:.html
相关问题