【问题标题】:Spring simply rendering an html pageSpring简单地渲染一个html页面
【发布时间】:2014-08-15 16:13:06
【问题描述】:

问题:

使用 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 呈现网页吗?我错过了什么?

提前致谢:)

【问题讨论】:

  • 请从请求中发布服务器日志。

标签: spring spring-mvc spring-boot


【解决方案1】:

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 指南。

【讨论】:

  • 你能明确告诉我应该为 maven 做什么吗?
  • 使用&lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;/dependency&gt;
  • @TejeshRaut 或者,您可以转到 start.spring.io 并下载生成的包以查看 maven 文件中需要什么。
【解决方案2】:

“如何让 Spring Boot 呈现网页?”的最简单答案问题是:将您的 home.html 文件放在 src/main/resources/static/ 文件夹中。该页面将在/home.html URL 下提供。

更多详情in the documentation.

【讨论】:

  • 什么时候把 HTML 文件放在子目录“static”下,什么时候放在“templates”下?谢谢
【解决方案3】:

您可能没有配置模板引擎和视图解析器。在此处查看百里香的示例http://www.thymeleaf.org/doc/thymeleafspring.html 由于百里香模板是有效的 HTML 代码,反之亦然,您可以使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多