初學者在maven spring boot web項目中使用thymeleaf 模板,經常會遇到 “template might not exist or might not be accessible by any of the configured Template Resolvers”這個問題,讓人很頭疼。其實這個錯誤的描述很清楚:
第一、模板不存在 ,第二、模板無法被解析器解析
帶着這兩個問題來找答案:
首先確定在Maven的資源管理文件中 pom.xml確保引入 spring-boot-starter-thymeleaf這個jar包,如果配置中有,它會自動下載到本地庫。
<!-- 引入 thymeleaf 模板依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
接下來在application.properties 中添加如下配置:
spring.thymeleaf.mode=HTML spring.thymeleaf.cache=true spring.thymeleaf.enabled=true spring.thymeleaf.encoding=utf-8 spring.thymeleaf.prefix=/resources/templates/ spring.thymeleaf.suffix=.html #文件后綴為.html或.jsp都可以,取決於/resources/templates/下對應的文件
有了以上這兩步就沒問題了,如下是項目的目錄結構
Spring 啟動類及MVC的 控制器部分代碼:

package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.example.bean.User; @Controller @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.print("app init"); } @RequestMapping("/hello") @ResponseBody String home() { System.out.print("hello"); return "Hello ,spring boot!"; } @RequestMapping("/") public String index() { System.out.print("index"); return "index"; } @RequestMapping("/userLogin") public String userLogin(Model model) { User user = new User("guozhong",30); model.addAttribute("user",user); return "userLogin"; } }
瀏覽器訪問: