【问题标题】:How to make an html-file appear on localhost with Spring Boot?如何使用 Spring Boot 使 html 文件出现在本地主机上?
【发布时间】:2016-11-08 08:30:59
【问题描述】:

我正在使用 Spring Boot 并且有一个 html 文件“index.html”,并且我有一个类“Functions”。基本上,我想要发生的是,当函数类运行时,当我转到 localhost:8080 时,html 模板出现在 localhost。 我该怎么做?

这是函数类的一部分:

public class Functions{
   @RequestMapping("/")
   public void getHomepage(){
      //Return the html-template
   }

}

html 文件名为“index.html”,位于 src/main/resources/static 文件夹中。

谢谢!

【问题讨论】:

  • return "index"; 放入getHomepage() 方法的主体中。请参阅此Spring Web MVC Getting Started 教程。模板应位于 src/main/resources/templates 而不是 src/main/resources/static
  • 非常感谢!我现在就试试
  • @Jesper 是对的。我根据这个教程创建了一个项目,非常有帮助:springframework.guru/…
  • 请注意,您必须更改返回类型。

标签: java html spring spring-mvc


【解决方案1】:

首先,将index.html模板文件放入src/main/resources/templates而不是src/main/resources/static

您的类Functions 必须是Spring MVC 控制器;您可以通过添加 @Controller 注释使其成为控制器。在getHomepage()方法中返回模板名称:

@Controller
public class Functions {
    @RequestMapping("/")
    public String getHomepage() {
        return "index";
    }
}

这是所有基本的 Spring Web MVC;在 Spring 网站和 reference documentation 上查看类似 Serving Web Content 的教程。

【讨论】:

  • 我会详细看教程。现在,当我将返回类型更改为字符串时,添加了@Controller,并将“index.html”放入“模板”中。但是,当我只是复制您的代码并转到本地主机时,它只会在屏幕上显示索引。像一个字符串。我仍然没有看到 html。
  • 您是在Functions 类或方法getHomepage() 上使用@RestController@ResponseBody,还是修改了Spring 配置使其无法以默认方式工作?
  • 感谢您的再次回复!我没有做过任何这些事情。即使我在 maven 中放入了 spring-boot-starter-thymeleaf 依赖项,Spring Boot 似乎也无法识别 Tymeleaf。当我转到 html 文件并查看命名空间 xmlns:th="thymeleaf.org" 时,它表示从未使用过命名空间声明。
  • 没关系,这只是意味着您的模板中没有任何<th:...> 标签——这并不意味着Spring Boot 没有找到Thymeleaf。如果没有看到您项目的确切结构和设置,我无法判断到底出了什么问题。
  • 好的,谢谢您的信息!对于所有的帮助,我会继续寻找问题所在:)
猜你喜欢
  • 2019-03-12
  • 2014-10-20
  • 2016-11-24
  • 1970-01-01
  • 2020-04-03
  • 2019-07-13
  • 2021-05-15
  • 2019-03-15
  • 2022-11-17
相关资源
最近更新 更多