如何在Spring Controller路由中呈现html文件?

我正在使用IntelliJ,Maven和Spring构建本地Web服务器。当我返回Spring的@Controller /resources/static/jimi.html的位置时,Java服务器只是将String打印到屏幕上,而不是呈现html文件。

我是spring框架的新手。我按照start.spring.io教程设置了Java Web应用程序。目前,我已经使用IntelliJ(默认)设置并运行了基础程序。我的问题如下:我只能弄清楚如何成功将String类型返回到localhost:8080 / jimi。

我通常使用Python编写代码,并且我了解到Spring框架具有@Controller包装器,类似于Python中的flask @ app.route包装器。我想返回一个html文件而不是一个String,但是不知道怎么做。我编写了以下代码,可以在本地Maven服务器上成功提供String内容:

@Controller
public class ShelfController {

    @GetMapping("/")
    @ResponseBody
    public String home(){
        return "You are here";
    }

    @GetMapping("/jimi")
    @ResponseBody
    public String jimi(){
        //STUCK HERE
    }
}

第一个路由“ localhost:8080 /”工作正常,并在屏幕上显示“您在这里”字符串。打开检查器时,我看到它正在将String返回到此自动生成的html文件的正文中。

<html>
<head><head>
<body>
    "You are here"
</body>
</html>

文件结构如下:

src ____ main ____ java ____ com.book.shelf ____ ShelfController.java
    \         \
     \         \__ resources ____ templates ...
      \                      \ 
       \__test ...            \__ static ____ jimi.html

我正在寻找类似于Python-flask的(Java-Spring)代码

@app.route("/jimi")
def jimi():
    return render_template("jimi.html")

它将以给定的路由127.0.0.1:8080/jimi返回jimi.html模板

taisen518 回答:如何在Spring Controller路由中呈现html文件?

答案是:通过实现百里香。

1)将jimi.html移至src / main / resources / templates存储库

2)函数应返回字符串“ jimi”(不包含“ .html”)

3)从“ / jimi”路线中删除@ResponseBody注释

4)jimi.html需要

5)将thymeleaf spring依赖项添加到pom.xml

//SHELFCONTROLLER.JAVA CODE
@Controller
public class ShelfController {

    @GetMapping("/")
    @ResponseBody
    public String home(){
        return "You are here";
    }


    @GetMapping("/jimi")
    public String jimi(){
        return "jimi";
    }
}

//JIMI.HTML CODE
<!-- HTML CODE -->
<html xmlns:th="http:www.thymeleaf.org" lang="en">
  <head></head>
  <body>Hendirx is a Voodoo Chile</body>
</html>

//ADD TO POM.XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
本文链接:https://www.f2er.com/3122978.html

大家都在问