SpringBoot如何返回(访问)到template下面的html页面

SpringBoot默认html是static下面访问的,不能直接访问tempate下面资源的,而且SpringBoot默认不支持JSP页面的,推荐使用thymeleaf模板,这里先不讲thymeleaf,我们直接先访问普通html页面。

1.首页在POM.XML文件加上thymeleaf依赖:

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

2.然后application.yml增加视图前缀:

spring:
  thymeleaf:
    prefix:
      classpath: /templates   # 访问template下的html文件需要配置模板,映射
    cache: false # 开发时关闭缓存,不然没法看到实时页面

3.在template文件下创建一个index.html页面

index.html内容简单写一个内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<span>欢迎来到demo</span>
</body>
</html>

4.在启动类写一个@Controller,返回index.html

5.项目启动起来我们直接访问localhost:8080/hello

发现就是返回页面。展示页面内容。 2019-08-02补充说明:默认是index.html可以世界访问,其它的请用MVC模式访问页面,即在Controller中,返回对应的页面。

经验分享 程序员 微信小程序 职场和发展