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 楼答案
我测试了你的代码,没有得到“helloworld”作为对thymeleaf和html的静态响应。但是我被打印了字符串
“helloworld.html”,带有注释@ResponseBody
作为控制器,方法返回一个字符串,在您的示例中,该字符串是误导性的“helloworld.html”