【问题标题】:Thymeleaf: th:value - if property existsThymeleaf: th:value - 如果属性存在
【发布时间】:2017-05-13 11:59:33
【问题描述】:

我想创建一个隐藏的输入框:

<input type="hidden" th:value="${map.version} name="version"/>

问题:
version 可能还有一个不存在的属性(我说的不是null!)。
现在我收到一个异常Property or field 'version' cannot be found on object

我需要什么:
如果不存在,th:value 语句可能会被忽略或标签被移除

澄清:
map 来自 Spring Controller 中的处理程序方法:

@PostMapping("/new")
public String handleMapFormSubmit(
    @ModelAttribute("map") @Valid AddMapCommand command, BindingResult result ) {

    if ( result.hasErrors() ) {
        return "map-form";
    }

    // do some stuff

    return ".....";
}

问题是此处理程序方法中的map (AddMapCommmand) 不包含 version 属性。在另一个处理程序方法(UpdateMapCommand)中它确实如此。重点是在几乎相似的两种场景中重用map-form thymeleaf 模板。

【问题讨论】:

  • version 是您要添加的地图的键吗?如果是这样,请查看stackoverflow.com/questions/28621301/…
  • 是的。但它可以存在也可以不存在。我会看看链接谢谢。
  • 我试过${map['version']}。它可以在设置版本时工作,但如果没有则抛出异常。
  • 在我的例子中,map 不是地图 (HashMap),而是 GameMap,一个自己的域类型,其中包含属性(其中一个是版本)

标签: spring-mvc thymeleaf


【解决方案1】:

您可以尝试将instanceof 运算符仅用于包含该属性的对象:

<input type="hidden" 
 th:if="${map instanceof T(my.project.UpdateMapCommand)}" 
 th:value="${map.version} name="version">

为了将来参考,使用像 map 这样的变量会非常令人困惑,并且不会让读者将其解释为 java.util.Map。您应该更改您的 map 变量名称以减少混淆,或者至少是为了在 StackOverflow 上提出问题。

【讨论】:

  • 这为我指明了正确的方向。谢谢。我同意地图命名。我只是赶时间。无论如何都欢呼!
  • Thymeleaf 中是否有类似:object.hasAttribute('version') 的内容?
猜你喜欢
  • 1970-01-01
  • 2021-06-09
  • 2014-02-27
  • 2015-03-07
  • 2018-12-18
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多