【问题标题】:Thymeleaf: handling maybe-existing properties of a model?Thymeleaf:处理模型可能存在的属性?
【发布时间】:2017-05-14 12:35:29
【问题描述】:

问题:
我在 Spring MVC 中有一个 Thymeleaf 模板,我想将其用于两件事:
1) 用于在数据库中创建新实体
2) 用于更新数据库中的现有实体

这两个用例之间只有一个微小的区别:数据库中的实体有一个 version(乐观锁定)属性集,所以我想记住这个版本作为隐藏字段模板,这很容易做到。

为了更好地理解我的出发点是我用于创建新实体的处理程序代码:

@GetMapping("/new") 
String showMapFormForAdd( Model model ) { 

    model.addAttribute( "map", null ); // PASS null into it 

    return "map-form"; // same template 
} 

这是更新现有实体的代码:

@GetMapping("/{mapId}/update") 
public String showMapFormForUpdate( @PathVariable Long mapId, Model model ) { 

    GameMap map = mapService.findMap( mapId ); 

    model.addAttribute( "map", map ); // PASS the real map into it (with version!!!) 

    return "map-form"; // same template 
} 

下面是 Thymeleaf 模板中隐藏版本字段的代码

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

但是,当模板在第一个处理程序(创建)之后呈现时,我得到一个异常,即属性版本不存在(它是真的,它不存在)。

问题:
我如何告诉 Thymeleaf,仅在注入 Thymeleaf 的“地图”模型中存在 version 属性时才查询版本并将其设置为隐藏字段中的值?

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    您可以添加条件 th:value

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 2016-07-12
      • 2014-03-10
      • 2013-08-27
      • 2018-12-16
      相关资源
      最近更新 更多