问题:
使用 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 {
}
这个 Controller 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!
.
问题:
我知道我缺少渲染 View 的方式,但我在 stackoverflow 上搜索了几个问题,但尚未找到解决方案。
有人可以解释一下如何让 Spring 渲染网页吗?我缺少什么?
提前致谢:)
最佳答案
Spring Boot 将自动使用并配置 Thymeleaf 作为 View 渲染引擎,只要它位于类路径上。 要将其放在类路径上,请使用
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
View (根据您使用的 Controller ),您需要将其放在 /resources/templates
下.
有关完整示例,请查看 this指南。
关于Spring简单地渲染一个html页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25330084/