首页 > 解决方案 > 如何评估百里香模板中嵌套对象的字段?

问题描述

给定两个对象:

public class MVCmodel {
   UUID uuid;
   NestedObject nestedObject = new NestedObject ();
}

public class NestedObject {
   @Size(min = 2, max = 99)
   String name = "";
}

百里香叶模板

            <tr>
                <td>
                   <input required="true" type="text" th:name="name"
                           th:value="${mVCmodel.getNestedObject.getName()}"
                   >
                   <span th:if="${#fields.hasErrors('name')}"
                    th:errors="${mVCmodel.getNestedObject().getName()}"
                   >Name Error
                   </span> 
                </td>
            </tr>

我收到此错误:评估 SpringEL 表达式的异常:“fields.hasErrors('name')”

SpringEL 尝试评估 mVCmodel.name 并且必须失败,因为 MVCmodel 中没有字段名称。

如何评估字段 mVCmodel.nestedObject.name?

标签: spring-bootspring-mvcthymeleaf

解决方案


If you're not using in a form using th:object, you need to use #fields.hasErrors like this:

${#fields.hasErrors('${mVCmodel.nestedObject.name}')}

If you are using th:object, something like this should work:

${#fields.hasErrors('nestedObject.name')}

Difficult to tell from the code you posted. Do you have getters and setters for each of your fields?


推荐阅读