You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot请求/home触发TemplateInputException问题求助

解决Thymeleaf 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 a name parameter like ?name=YourName)
  • You should see the "Hello, [Name]!" message without any exceptions.

内容的提问来源于stack exchange,提问作者mUBUNTU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:29:06