org.thymeleaf.exceptions.TemplateInputException: Error resolving template [index], template might not exist or might not be accessible by any of the configured Template Resolvers
我的代碼:
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/demo") public class IndexController { @GetMapping(value = "index") public String showIndex(Model model) { model.addAttribute("h1_text", "this is a index page!"); return "index"; } }
解決辦法,返回路徑前加上 / :
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/demo") public class IndexController { @GetMapping(value = "index") public String showIndex(Model model) { model.addAttribute("h1_text", "this is a index page!"); return "/index"; } }
遇到類似問題可以加上或去掉 / 試下。
其他注意問題:
1、在入口Application不要忘記加入你的包
@SpringBootApplication(scanBasePackages = {"com.example.controller"})
2、@Controller 、@RestController、@ResponseBody 三者使用注意你是返回頁面、字符串還是JSON數據
3、使用thymeleaf作為模板文件,要求HTML格式必須為嚴格的html5格式,必須有結束標簽,否則會報錯,將其改為非嚴格的即可:LEGACYHTML5
application.properties
#是否開啟緩存,開發時可設置為false,默認為true spring.thymeleaf.cache=false #檢查模板是否存在,默認為true spring.thymeleaf.check-template=true #檢查模板位置是否存在,默認為true spring.thymeleaf.check-template-location=true #模板文件編碼,UTF-8 spring.thymeleaf.encoding=UTF-8 #模板文件位置 spring.thymeleaf.prefix=classpath:/templates #Content-Type配置 spring.thymeleaf.servlet.content-type=text/html #模板文件后綴 spring.thymeleaf.suffix=.html #啟用MVC Thymeleaf視圖分辨率 spring.thymeleaf.enabled=true #模板編碼 spring.thymeleaf.mode=LEGACYHTML5 #應該中解決方案中排除的視圖名稱的逗號分隔列表 spring.thymeleaf.excluded-view-names=
application.yml
spring.thymeleaf.content-type: text/html
spring.thymeleaf.cache: false
spring.thymeleaf.mode: LEGACYHTML5
pom.xml中加入
1 <dependency> 2 <groupId>net.sourceforge.nekohtml</groupId> 3 <artifactId>nekohtml</artifactId> 4 <version>1.9.22</version> 5 </dependency>