简体   繁体   English

Thymeleaf +静态资源+ @ResponseBody

[英]Thymeleaf + static resource + @ResponseBody

In Spring Boot, I've got the simplest controller ever, returning my view name: 在Spring Boot中,我得到了有史以来最简单的控制器,返回了我的视图名称:

@Controller
public class HelloController {

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

My helloworld.html file is placed in resources/static directory: 我的helloworld.html文件位于resources/static目录中:

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

And it works just fine - typing localhost:8080/hello prints "Hello world!" 而且效果很好-键入localhost:8080/hello “ Hello world!”。 in browser. 在浏览器中。

Then I add Thymeleaf dependency to pom.xml , rerun app and get TemplateInputException when typing the same address in browser. 然后在浏览器中键入相同的地址时,将Thymeleaf依赖项添加到pom.xml ,重新运行应用程序并获取TemplateInputException Which is fine I guess, as now the resources are searched by default in resources/templates directory. 我猜这很好,因为现在默认情况下会在resources/templates目录中搜索resources/templates

What I find weird, is when I add @ReponseBody annotation to controller method: 我发现很奇怪,是在我向控制器方法添加@ReponseBody注释时:

@Controller
public class HelloController {

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

Everything works again, I get "Hello world!" 一切恢复正常,我得到“ Hello world!” in browser. 在浏览器中。 But as I know, the @ResponseBody annotation is to put the returned value as a body of the response. 但据我所知, @ResponseBody批注是将返回的值作为响应的正文。 So why it miraculously caused that the view file can be found again? 那么,为什么奇迹般地导致可以再次找到视图文件呢?

I tested your code and I do not get "Hello World" as response with thymeleaf and html placed under static. 我测试了您的代码,但没有将百里香和html放在静态下作为响应“ Hello World”。 But I get printed the string 但是我得到了打印的字符串

"helloworld.html" with annotated @ResponseBody 带注释的@ResponseBody的“ helloworld.html”

as your controller method returns a String which in your case is the misleading "helloworld.html" 当您的控制器方法返回一个String时,在您的情况下该字符串是误导性的“ helloworld.html”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM