今日在學習Spring Boot thymeleaf 中踩了個坑,始終報錯 Thymeleaf org.thymeleaf.exceptions.TemplateInputException: Error resolving template [Success.]
我們知道thymeleaf在查找資源的時候默認會到templates文件夾下,查找“.html”結尾的文件。而我在 templates 文件夾下已經創建了一個文件 “success.html”,但是始終報錯,我的Controller層代碼如下:
@Controller public class HelloController { @RequestMapping("/success") public String success(){ //classpath:/templates/success.html return "Success."; } }
經過反復查詢才發現問題的根本還是對thymeleaf的工作原理掌握不明白,一味的照搬教程,導致了錯誤發生。
thymeleaf在查找資源時會默認到templates下查找“.html”的文件來加載,如果templates下有多個html文件那么該加載哪個呢?這時候thymeleaf會根據Controller中方法的返回值來定位具體文件,也就是說Controller方法返回值就是具體的文件名!
知道了這個原理再檢查代碼發現 我的返回值多寫了一個小數點 "." 而正是這個小數點導致了thymeleaf會去templates下查找名字為“success..html”的文件,自然是找不到的。
return "Success.";
實際上,報錯信息也給了明顯的提示,只是剛開始學不了解原理沒有注意到提示信息中的小數點 “.”
Error resolving template [Success.]
學習任何一門技術首先要了解其中的原理,不能放過每一個細節,這樣才能學的扎實。