Spring简单地渲染一个html页面

2023-12-09

问题:

使用 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";
    }
}

你好!显示在日志中。

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

问题:

我知道我缺少渲染视图的方式,但是我在 stackoverflow 上搜索了几个问题,但还没有找到解决方案。

有人可以解释一下如何让 Spring 渲染网页吗?我缺少什么?

提前致谢 :)


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.htmlview(根据您使用的控制器),您需要将其放在/resources/templates.

有关完整的示例,请查看this guide.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring简单地渲染一个html页面 的相关文章

随机推荐