Thymeleaf +静态资源+ @ResponseBody

时间:2018-08-23 05:58:32

标签: java spring-mvc thymeleaf

在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会显示“ Hello world!”在浏览器中。

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

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

@Controller
public class HelloController {

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

一切正常,我得到“你好,世界!”在浏览器中。但据我所知,@ResponseBody批注是将返回的值作为响应的主体。那么,为什么神奇地导致再次找到视图文件呢?

1 个答案:

答案 0 :(得分:0)

我测试了您的代码,但没有将百里香和html放在静态下作为响应“ Hello World”。但是我打印出了字符串

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

因为您的控制器方法返回一个String,在您的情况下,该字符串是具有误导性的“ helloworld.html”