Kur*_*usu 0 java spring thymeleaf
新手问题<input>,我想使用 Thymeleaf 显示用户的嵌套属性
我尝试通过向List我的表单发送一个User 对象来访问它
<select id="user">
<option value="" th:text="-Select-"></option>
<option
th:each="user: ${users}"
th:value="${user.id}"
th:text="${user.name}"
th:attr="data-department=${user.department.name}">
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Thymeleaf 可以定位嵌套的部门对象(返回[object, Object]),但是当尝试访问部门名称时,尝试访问部门的 SpringExpressionLanguage 异常name。
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'name' cannot be found on null
Run Code Online (Sandbox Code Playgroud)
我仍在浏览文档,但还没有找到如何访问它,这可能非常简单。有任何想法吗?
显然,其中一个用户没有部门,因此部门是null。Thymeleaf 无法获取 null 属性的值。这就是你得到错误的原因。尝试检查部门不在null输出之前:
<select id="user">
<option value="" th:text="-Select-"></option>
<option
th:each="user: ${users}"
th:value="${user.id}"
th:text="${user.name}"
th:attr="data-department=${user.department!=null}?${user.department.name}:'not specified'">
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5547 次 |
| 最近记录: |