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

Spring MVC Java项目中使用Thymeleaf出现500内部服务器错误

Thymeleaf模板解析失败(TemplateInputException)导致500错误的排查与解决

针对你遇到的TemplateInputException引发的500内部服务器错误,以下是常见原因及对应解决方法:

1. Thymeleaf命名空间拼写错误

你的HTML中Thymeleaf命名空间存在错误:

xmlns:th="http://thymeleaf.org"

正确的命名空间需包含www前缀,修正为:

xmlns:th="http://www.thymeleaf.org"

命名空间错误会导致Thymeleaf无法识别th:*系列标签,直接触发模板解析失败。

2. 模型数据未正确传递或类型不匹配

检查控制器方法是否将people集合正确注入到Model中:

@GetMapping("/people")
public String getPeople(Model model) {
    List<Person> peopleList = personService.getAllPeople();
    model.addAttribute("people", peopleList); // 必须确保传递的是可迭代集合
    return "people/index";
}
  • 若未执行model.addAttribute("people", ...),Thymeleaf解析${people}时会找不到变量
  • 若传递的不是集合/数组等可迭代对象(如单个Person实例或null),th:each会抛出迭代异常

3. Person类Getter方法不符合JavaBean规范

Thymeleaf依赖JavaBean规范获取对象属性,检查你的Person类:

public class Person {
    private Long id;
    private String name;

    // 必须是首字母大写的标准Getter方法
    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    // 对应Setter方法(可选,根据业务需求)
    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}

若Getter方法名不符合规范(如写成getid()或getname()),Thymeleaf无法通过反射获取属性值,会引发解析错误。

4. 模板文件路径配置不匹配

错误提示模板路径为ServletContext resource [/people/index.html],检查Spring MVC视图解析器配置:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("/templates/"); // 模板文件所在前缀路径
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    // 其他相关配置...
}

确保模板文件实际存放在src/main/resources/templates/people/index.html路径下,路径不匹配会导致Thymeleaf找不到模板文件,触发解析异常。

内容的提问来源于stack exchange,提问作者Никита Шпагин

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:01:22