Spring Boot请求/home触发TemplateInputException问题求助
Hey there! Let's dig into why you're hitting that TemplateInputException when accessing /home.
核心问题分析
First off, your custom ClassLoaderTemplateResolver in WebConfig has a small but critical issue with the prefix setting. Spring Boot's default Thymeleaf setup expects templates to be under classpath:/templates/, but your resolver is using just templates/—this means Thymeleaf is looking in the wrong location for your home.html file.
Additionally, there's a syntax error in your home.html template that would cause issues once the template is found: the expression ~{name} is incorrect for variable substitution—you should use ${name} instead.
解决方案步骤
1. 修正WebConfig中的模板解析器前缀
Update your ClassLoaderTemplateResolver to use the correct prefix that matches Spring Boot's default path:
@Configuration @ComponentScan(basePackages = "be.mubuntu.dev.cbrapi") public class WebConfig implements WebMvcConfigurer { @Bean public ClassLoaderTemplateResolver yourTemplateResolver() { ClassLoaderTemplateResolver configurer = new ClassLoaderTemplateResolver(); // Fix the prefix to match Spring Boot's default location configurer.setPrefix("classpath:/templates/"); configurer.setSuffix(".html"); configurer.setTemplateMode(TemplateMode.HTML); configurer.setCharacterEncoding("UTF-8"); configurer.setOrder(0); configurer.setCacheable(false); configurer.setCheckExistence(true); return configurer; } }
2. 修复home.html中的表达式错误
Change the th:text attribute to use the correct variable expression syntax:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <!-- Use ${name} instead of ~{name} for variable substitution --> <p th:text="'Hello, ' + ${name} + '!'" /> </body> </html>
3. 可选:移除自定义WebConfig(如果不需要特殊配置)
If you don't need custom Thymeleaf settings beyond the Spring Boot defaults, you can actually delete your WebConfig class entirely. Spring Boot auto-configures Thymeleaf with the correct template path out of the box, which would avoid this kind of path mismatch issue.
验证步骤
After making these changes:
- Rebuild and restart your application
- Access
http://localhost:8080/home(or add anameparameter like?name=YourName) - You should see the "Hello, [Name]!" message without any exceptions.
内容的提问来源于stack exchange,提问作者mUBUNTU

