无法使用Thymeleaf加载部分模板,请求排查错误原因
Hey there, let's work through why your header content isn't showing up in index.html. Here are the most likely issues and their fixes:
1. You're accessing the static HTML file directly (not via a Spring Controller)
This is the most common mistake. If you're visiting http://localhost:8080/index.html directly, Spring Boot treats it as a static resource and doesn't process it with the Thymeleaf engine. All th:* attributes (like th:insert and th:fragment) get ignored entirely, so your header fragment never gets inserted.
Fix:
Create a simple controller to map your desired URL to the index template:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/") public String showHomePage() { return "index"; // Tells Spring to use Thymeleaf to render templates/index.html } }
Now visit http://localhost:8080/ instead of the direct .html URL.
2. Thymeleaf Cache is Enabled (Development Environment Issue)
By default, Spring Boot enables Thymeleaf caching (great for production, not so much for development). If you made template changes without restarting your app, the cached old version might be serving up instead of your updated code.
Fix:
Add this line to your application.properties file to disable caching during development:
spring.thymeleaf.cache=false
Restart your app after adding this setting.
3. Double-Check Fragment Reference & File Paths
While your syntax looks correct, confirm these details:
- Your fragment is named
headerinheader.html(th:fragment="header"), so the referenceth:insert="header :: header"is valid (both files live in the roottemplates/folder, no extra path needed). - Make sure both files are actually in
src/main/resources/templates/(note: file paths are case-sensitive on Linux/macOS).
4. Verify Your Thymeleaf Dependency
Your Gradle dependency compile('org.springframework.boot:spring-boot-starter-thymeleaf') is correct (though newer Gradle versions use implementation instead of compile, but this won't break older setups). Just ensure your build completed successfully and the dependency was downloaded properly.
Once you fix the controller issue (the most probable root cause), your "2016 Header" should render correctly above the user registration form.
内容的提问来源于stack exchange,提问作者SBN AB

