Spring只是渲染一个html页面

Gus*_*obo 4 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).
Run Code Online (Sandbox Code Playgroud)

是)我有的:

我有这个Main类:

// 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);

    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个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 {

}
Run Code Online (Sandbox Code Playgroud)

而这个控制器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";
    }
}
Run Code Online (Sandbox Code Playgroud)

你好!显示在日志中.

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

问题:

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

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

提前致谢 :)

geo*_*and 8

Spring Boot会自动使用和配置Thymeleaf作为视图渲染引擎,只要它在类路径上即可.把它放在classpath上使用

compile("org.springframework.boot:spring-boot-starter-thymeleaf")
Run Code Online (Sandbox Code Playgroud)

在gradle构建文件中.

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 使用`<dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-thymeleaf </ artifactId> </ dependency> (3认同)

kry*_*ger 5

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

文档中的更多细节.