Spring Boot+Thymeleaf 3展示Bean时出现SpEL表达式异常求助
问题排查与解决方案
看起来你的问题出在两个关键地方:Thymeleaf循环对象错误,以及未初始化关联的Cities对象,导致Spring EL解析时出现混乱。
1. 异常根源分析
你在控制器中传递的是单个Cars对象,但Thymeleaf里却写了<tr th:each="car, stat : ${cars}">——这相当于在遍历单个Cars实例的属性(而不是它的locations列表),这种错误的遍历逻辑会让Thymeleaf的表达式解析器陷入混乱,最终抛出cities.id找不到的异常(因为解析时错误地把某个集合当成了cities对象)。
另外,你直接new Cars()时,cities属性是null,直接访问cities.id会触发空指针相关的解析错误。
2. 具体修复步骤
步骤1:修复控制器,初始化关联对象
在创建Cars实例时,主动初始化Cities对象,避免null值导致的解析问题:
public String getNewCarsTemplate(Model model) { Cars cars = new Cars(); cars.setCities(new Cities()); // 初始化Cities,避免访问null属性 model.addAttribute("cars", cars); return "your-template-path"; // 记得返回你的视图名称 }
步骤2:修正Thymeleaf的循环逻辑
循环应该针对Cars对象的locations列表,而不是Cars本身,同时调整表单字段的绑定表达式:
<form id="carsForm" action="#" th:action="@{/template/new/cars}" th:object="${cars}" th:method="post"> ... <input type="hidden" th:field="*{cities.id}" > <input id="carsCities" class="form-control js-typeahead" type="search" placeholder="Type partial value" th:field="*{cities.name}" autocomplete="off" > ... <table id="locationsTable" class="table table-striped table-hover responsive"> <thead> <tr> <th th:text="#{name}">Name</th> <th></th> </tr> </thead> <tbody> <!-- 遍历cars的locations列表,循环变量改为location --> <tr th:each="location, stat : *{locations}"> <td> <input type="hidden" th:id="${'locationId-'+stat.index}" th:field="*{locations[__${stat.index}__].id}" /> <input type="text" class="form-control" th:id="${'locationName-'+stat.index}" th:placeholder="#{name.placeholder}" placeholder="Name" th:field="*{locations[__${stat.index}__].name}" /> </td> <td class="align-middle"> <i class="fas fa-trash-alt"></i> </td> </tr> </tbody> </table> </form>
步骤3:确认实体类的getter/setter
最后检查Cities、Cars、Locations类的所有属性(比如id、name)都有public的getter和setter方法,Spring EL需要通过这些方法访问属性,否则也会抛出“找不到属性”的异常。
如果后续需要动态添加新的location行,你还需要补充前端的JS逻辑,但当前的错误已经可以通过上述步骤解决。
内容的提问来源于stack exchange,提问作者robert trudel
相关产品推荐
相关产品推荐

