Spring只是渲染一个html页面

时间:2014-08-15 16:13:06

标签: spring spring-mvc spring-boot

问题:

使用Spring 4,我在访问网页时得到了这个

Whitelabel Error Page

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

Fri Aug 15 16:41:29 BST 2014
There was an unexpected error (type=Not Found, status=404).

我有什么:

我有这个主要课程:

// src/main/java/abc/Main.java
package abc;

import abc.web.WebAppConfig;
import org.springframework.boot.SpringApplication;

public class Main {
    public static void main(String[] args) {
        SpringApplication.run(WebAppConfig.class);

    }
}

然后我有了这个WebAppConfig.class(目前只有一些配置注释):

// src/main/java/abc/web/WebAppConfig.java
package abc.web;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class WebAppConfig {

}

这个控制器HomeController.java:

// src/main/java/abc/web/HomeController.java
package abc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@RequestMapping("/")
public class HomeController {

    @RequestMapping(method = GET)
    public String home() {
        System.out.println("HELLO !!");
        return "home";
    }
}

你好!显示在日志中。

最后我在src/main/java/abc/webapp/home.html处有一个html文件,只有一些html标记包含p标记Hello, world!

问题:

我知道我错过了呈现视图的方式,但我在stackoverflow上搜索了几个问题,但尚未找到解决方案。

有人可以解释我如何让Spring渲染网页?我错过了什么?

提前致谢:)

3 个答案:

答案 0 :(得分:8)

Spring Boot会自动使用并配置Thymeleaf作为视图渲染引擎,只要它在类路径上即可。 要将它放在类路径上,请使用

compile("org.springframework.boot:spring-boot-starter-thymeleaf")
在gradle构建文件中。

如果您正在使用maven添加依赖项:

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

为了显示home.html视图(根据您使用的控制器),您需要将其放在/resources/templates下。

有关完整示例,请查看this指南。

答案 1 :(得分:5)

最简单的答案是&#34;如何让Spring Boot渲染网页?&#34;问题是:将您的home.html文件放在src/main/resources/static/文件夹中。该页面将在/home.html网址下提供。

更多详情in the documentation

答案 2 :(得分:0)

您可能未配置模板引擎和查看解析程序。请参阅此处与thymeleaf的示例http://www.thymeleaf.org/doc/thymeleafspring.html 由于thymeleaf模板是有效的HTML代码,反之亦然,您可以使用它。