有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Thymeleaf+静态资源+@ResponseBody

在Spring Boot中,我得到了有史以来最简单的控制器,返回了我的视图名称:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "helloworld.html";
    }
}

我的helloworld.html文件位于resources/static目录中:

<html>
<body>
Hello world!
</body>
</html>

而且它工作得很好-键入localhost:8080/hello打印“你好,世界!”在浏览器中

然后我将Thymeleaf依赖项添加到pom.xml,重新运行app并在浏览器中键入相同地址时获取TemplateInputException。我想这很好,因为现在默认情况下在resources/templates目录中搜索资源

我觉得奇怪的是,当我向控制器方法添加@ReponseBody注释时:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "helloworld.html";
    }
}

一切恢复正常,我听到“你好,世界!”在浏览器中。但正如我所知,@ResponseBody注释将返回的值作为响应的主体。那么,为什么它奇迹般地导致视图文件再次被找到呢


共 (1) 个答案

  1. # 1 楼答案

    我测试了你的代码,没有得到“helloworld”作为对thymeleaf和html的静态响应。但是我被打印了字符串

    “helloworld.html”,带有注释@ResponseBody

    作为控制器,方法返回一个字符串,在您的示例中,该字符串是误导性的“helloworld.html”