thymeleaf - 将选择变量表达式 *{foo} 传递给表达式实用程序对象

thymeleaf - passing a Selection Variable Expression *{foo} to an Expression Utility Object

我有一个 spring 支持的表单,其模型对象 Foo 包含 Bar

<form action="#" th:action="@{/some/action}" th:object="${foo}" method="post">

现在,我想做这样的事情:

<input type="text" id="bar.createdAt" name="bar.createdAt" th:value="*{bar.createdAt} ? ${#dates.format(bar.createdAt, #messages.msg('app.dateformat.datetime'))}"/>

但抛出以下解析异常:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#dates.format(bar.createdAt, #messages.msg('app.dateformat.datetime'))" (registration:93)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
root cause

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#dates.format(bar.createdAt, #messages.msg('app.dateformat.datetime'))" (registration:93)
    org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:161)
    org.thymeleaf.standard.expression.VariableExpression.executeVariable(VariableExpression.java:154)
    org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:59)
root cause

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 7): Property or field 'createdAt' cannot be found on null
    org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:211)
    org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:85)
    org.springframework.expression.spel.ast.PropertyOrFieldReference.access[=12=]0(PropertyOrFieldReference.java:43)
    org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:341)

我已经尝试过: ...#dates.format(*{bar.createdAt}..., ...#dates.format(__*{bar.createdAt}__...但是 none 已经解决了。

同样没有表单(直接访问视图模型对象)工作正常。

知道什么是正确的结构吗? 提前致谢!!!

我认为线索就在一行中:

Property or field 'createdAt' cannot be found on null

您确定 bar 不为空吗?

而不是:

${#dates.format(bar.createdAt, #messages.msg('app.dateformat.datetime'))}

改为:

*{#dates.format(bar.createdAt, #messages.msg('app.dateformat.datetime'))}

这样实用程序对象将在最后一个选定对象的 bar 属性 上工作,在您的例子中是表单支持对象 ${foo}